In the course of your web design projects, you may come across a situation where you are required to show several lines of text inside a div element. You may also need these lines of text to be centered horizontally. For most of the part, using text-align:center inside the parent div willdo the trick. However, in some situations, you may need to have the text to have the text aligned vertically inside the div element.
There is a CSS attribute vertical-align:middle. The one point that confuses most people is that just setting a vertical-align:middle in a div for example does not vertical align the text inside.
1 2 3 4 5 6 7 8 9 10 11 12 |
<style> .contentbox { vertical-align:middle; height:200px; width:200px; border:1px solid #666; } </style> <div class="contentbox"> The quick brown fox jumps over the lazy dog. </div> |
Results in this:
The reason is, by default, a div is display:block And the text is to flow from top to bottom filling available space in such an element. Read about different display types here
When you change the display type to table-cell, it works as expected:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<style> .contentbox{ vertical-align:middle; text-align:center; height:200px; width:200px; border:1px solid #666; /*Note this:*/ display:table-cell; } </style> <div class="contentbox"> The quick brown fox jumps over the lazy dog. </div> <img class="alignnone size-full wp-image-58" alt="css vertical align working" src="http://csshunt.com/wp-content/uploads/2013/11/css-vertical-align-working.png" width="214" height="209" /> |
Vertical centering a div in another div
This gets trickier when you want to vertical center another div. One commmon method is to use CSS negative margin.
- We use absolute positioning to place the inner div at 50% of the parent div.
12345678910111213.container{height:200px;width:200px;border:1px solid #666;position:relative;}.inner{height:40px;background-color:#333;color:#fff;position:absolute;top:50%;}
- Then we use negative margin to pull half the height of the inner div up.
123456789.inner{height:40px;background-color:#333;color:#fff;position:absolute;top:50%;margin-top:-20px;}
Those are the common cases where you would like vertical align to work the way you want it. The first thing to remember is that you need to understand the basic layout concepts to really make it work. See the reference section below for more info.
Download Sample code: css vertical align