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

Q: Best method to vertically and horizontally align text within a div?

Q: What is the best and most robust method for vertically and horizontally aligning text within a div (preferably a responsive answer that works relative to the size of the div).

4 Answers

You can use this method with position relative and absolute```

<div class="test"> <p>center positioning</p> </div>

.test{ width:50%; height:300px; position:relative; background:red;

} .test p{ width:100px; height:20px; background:blue; position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; }```

or you can use the method width display table for the container and display table cell for the child. After that you align center the child with text-align:center and vertical-aling:middle;

div {
    text-align: center; // make text centered horizontally
    display: table-cell; // this says treat this element like a table cell
    vertical-align: middle; //now we can center vertically like in a TD
}

Of course there are several ways to do this.

  1. Absolute / relative positioning as George mentioned. Problem: Doesn't take into account multi-line text.

  2. Treat it like a table cell as Alexander mentioned. Problem: browser compatibility and it has the word "table" in the solution.

  3. just margins, padding, and line height. Problem: The div height adjusts if the text takes up more room. http://codepen.io/UncleRemus/pen/rdjBs

  4. Force the text to one line to keep from breaking options 1 & 3. http://codepen.io/UncleRemus/pen/xvywk

Thanks for the input people. I did attempt Georges method before BUT I did in-fact miss the :

top: 0;
rigth: 0;
bottom: 0;
left: 0;

...and then sat there scratching my head like a primate looking at a mirror?!

Thanks again, all good answers and of help.

Darren.