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

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.