Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Hi, I want to understand clearly one thing about centering a div at the middle of a page.

Following is the code:

position: absolute; left: 50%; top: 50%; margin-left: -285px; margin-top: -190px;

After applying positioning what actually is happening for that box, for which we are adding negative margin(half of the div width, if known and half of height if known).

3 Answers

because the starting point of the div is top left corner and not at the center. so when you applied left/top 50%, the top left corner will move to the center of the page. For example if page width is 1000px and height 800px, the div top left corner will stop at coordinate (x,y) which is (500px, 400px). you will notice the div is not centered and it looks like shifted to the right and lower. In order to make it center u will need to use margin with negative value to adjust it to the left/top because margin perform almost the same action in this case.

Steven Parker
Steven Parker
243,656 Points

Your understanding appears correct.

Another way to do the same thing, but without using the margin, would involve the calc function:

  position: absolute;
  top: calc(50% - 190px);
  left: calc(50% - 285px);

I want to know the theory or understanding behind the calculation, why we have to minus halves of width and height

Steven Parker
Steven Parker
243,656 Points

The 50% position is where the corner will be placed. So with the 50% by itself the element will not be centered, it's upper left corner will.

But if we subtract half of the element's own size (either by margin or calculating the position itself), then the center of the element will be centered instead of the corner.

Thank you both Steven and Iven