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

How to vertically center anything in using css3?

I want to vertically center some of my elements without knowing the height of parent div as the height of parent div which dynamically generate according to the content it contains. Pls... help!!!!!!!!!!!

2 Answers

Daniel Botta
Daniel Botta
17,956 Points

One option could be...

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

It also really depends on what you are working with. The element's display property and position property can affect how the vertical alignment is achieved. One consistent way which can be a bit ugly and annoying at times is align the element using a table by nesting it within a td tag.

I hope this helps.

One of the solutions is to give the parent container display:table; and to the content which needs to be centered display: table-cell; vertical-align: middle;

Another solution which also works is here http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

Hope it helps