# How do I calculate the new x y coordinate for a rectangle when centering it within a rectangle?

I need to center a rectangle inside another rectangle. I know the width and height of the parent rectangle, and I know the width and height of the child rectangle that needs to be centered. I need to find the x and y coordinate for the top left corner of the rectangle in the centered position. I don't know the current position of the child recatangle, I just need know the x y coordinate so I can place it in the center.

Please see the image below for further details.

What would be the correct formula to do this? ## 2 Answers

If the big rectangle is $a \times b$ (in your diagram $a=26, b=305$), and the smaller rectangle is $c \times d$ (here $(c,d)=(18,68)$), then your $x,y$ satisfy $2x+c=a,2y+d=b$ so that $(x,y)=((a-c)/2,(b-d)/2).$

A check: $(x,y)=(4,118.5)$ so the check would be $4+18+4=26$ and $118.5+68+118.5=305.$

Parent rectangle horizontal axis of symmetry lies at $26/2=13$ units from O and so should the horizontal axis of symmetry of the child rectangle.

Parent rectangle vertical axis of symmetry lies at $305/2=152.5$ units from O and so should the vertical axis of symmetry of the child rectangle.

Drawing these two lines intersecting (at say, O') on the parent rectangle and marking $68/2=34$ units to the left from O' to get point say 'a' and from 'a' marking $18/2=9$ units vertically upwards to get point point say 'b'. This point b will the left-upper corner of the child rectangle.