Vertical align block element inside block element
The popular question, “How to align vertically block inside block?”. Here’s an example of how to position a div in the middle of another div. The same way you can position vertically a block on the top or at the bottom. The main idea is that you have a container div with the same height
and line-height
values, for example, 100px
. Another div that is inside the container specifies its position (top, middle of bottom) using vertical-align
property.
HTML:
<div id="a"> <div id="b"></div> </div>? |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#a { display: block; width: 100px; height: 100px; line-height: 100px; float: left; border: 1px solid red; text-align: center; } #b { display: inline-block; background: gray; width: 50px; height: 50px; vertical-align: middle; } ? |
By the way, you can use this approach to align text within a div vertically.
The limitations of this approach is that you should specify fixed height
and line-height
values and cannot align vertically inside fluid height container. But there’re some other approaches to align vertically in fluid height containers, I’ll try to write about this in next articles.
Notice!! I’ve just checked this on XHTML DOCTYPE and it doesn’t work! In my case, it only works on HTML5.
Try it http://jsfiddle.net/F7X4u/.
[...] By the way, to center an image vertically you can use the approach like in the article Vertical align block element inside block element [...]