Vertical Centering with CSS
There are numerous methods available for vertically centering content using CSS. However, a large proportion of them require knowledge of the content's height. I find this less than desireable. Here are a couple of methods that don't have that shortcoming.
CSS Table Method
We’ll display our elements as table and table cell and then use the vertical-align property to center the content. Note: CSS tables are not the same as html tables.
HTML:
<div id="parent"> <div id="child">Content here</div> </div>
CSS:
#parent {display: table;} #child { display: table-cell; vertical-align: middle; }
Set the parent div to display as a table and the child div to display as a table-cell. We can then use vertical-align on the child div and set it’s value to middle. Anything inside this child div will be vertically centered.
The content can be dynamic as the div will grow with what’s placed inside. The downside of this method is it doesn’t work in older versions of IE, though there is a fix, which is to add display: inline-block to the child element:
#child { display: inline-block; }
Equal Top and Bottom Padding
HTML:
<div id="parent"> <div id="child">Content here</div> </div>
CSS:
#parent { padding: 5% 0; } #child { padding: 10% 0; }
In the css above I’ve set top and bottom paddings on both elements. Setting it on the child will make sure the contents in the child will be vertically centered and setting it on the parent ensures the entire child is centered within the parent.
I’m using relative measurements to allow each div to grow dynamically. If one of the elements or it’s content needs to be set with an absolute measurement then you’ll need to do some math to make sure things add up.
For example if the parent was 400px in height and the child 100px in height we’d need 150px of padding on both the top and bottom.
150 + 150 + 100 = 400
Using % could throw things off in this case unless our % values corresponded to exactly 150px.
This method works anywhere. The downside is that depending on the specifics of your project you may need to do a little math. However if you’re falling in line with the idea of developing flexible layouts where your measurements are all relative you can avoid the math.
Note: This method works by setting paddings on the outer elements. You can flip things and instead set equal margins on the inner elements. I tend to use padding, but I’ve also used margins with success. Which you choose would depend on the specifics of your project.