Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS CSS Layout Techniques Positioning Schemes Absolute Centering

Atlas AKIN
Atlas AKIN
1,675 Points

Absolute centering

I don't understand the coding to center an element with position:absolute.

In the video, the instructor makes the parent's position relative. I got this part.

Then he makes the children's(background image) position to be absolute and then offset it so that it would be in the middle. I got this part too.

So why did he need to set the margin to be auto?

Here is the code(partial) if anyone wants:

background-size:100%; top:0; bottom:0; right:0; left:0; margin:auto;

And by the way, why did we use background-size, even though we gave it specific width-length datas?

Isaac Asante
Isaac Asante
4,752 Points

It is because margin: auto; let's the browser automatically calculate the margin space equally on all sides. Think of when you want to center a wrapper div on a website, you set the left and right margins to auto.

What I don't understand is why Guil set all the offsets to zero? Why is that necessary with margin:auto? Wouldn't a top and left offset of zero just keep the image in the top left corner of the parent element?

Ehsan Raza
Ehsan Raza
263 Points

I know it's a late reply but the answer to your question for this "why did we use background-size, even though we gave it specific width-length datas?" That is because we are setting the space of the image to be e.g. 150px but the size of the image is not set yet. so we set the image size by using the "background-size". Try setting the image size by using "width" and "height" only and you will see that the image is way to large and you have to set its size. As far as i know this is only common with background-images where width of image will not be set by using "width" and "height". Just my view on this i'm no expert.

1 Answer

Hi Atlas,

You must set the margin to auto in order to overwrite any previous margin rules you have. If you attempt to center the element and have parent margin attributes, the child element will inherit the parent margin styling and will not truly be centered, unless you specifically add margin styling to the child element.