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

Chloe Brittain
PLUS
Chloe Brittain
Courses Plus Student 2,082 Points

Vertically center an object in a div?

I know vertical-align doesn't work for this. I want to vertically center an object, like an image, in a div - such as a logo vertically centered in a header. Is there an easy way to do this, like the margin:auto; that centers an object horizontally?

Thanks,

Chloe

4 Answers

Neville Barrett
Neville Barrett
6,141 Points

That seems like a much better method.

Easiest way I have found, and one I use all the time is this:

#element {
       position:absolute;
       top:50%;
       left:50%;
       -webkit-transform:translate(-50%,-50%);
       transform:translate(-50%,-50%);
}

I forgot where I found this solution (some blog), but yeah anyways it works like a charm.

note: this horizontally and vertically centers an element. If you just want vertical centering and the horizontal position to be somewhere else you can play with the "left" property value.

also: parent container should have its position set to relative in order for this to work.

Zen Hess
Zen Hess
6,700 Points

This rules, thanks for sharing.