Friday, March 20, 2015 - by

How to vertical center any element using CSS

There are a lot of techniques to center elements using CSS from having an element absolutely positioned and then using a mix of negative margin and percentage based top to vertically center the element. Sometimes using having the container’s display to table-cell has also been effective. But both of these techniques had their drawbacks of that the absolutely positioned elements were not dynamically content agnostic and table-cell used to fail most of the times on various elements.

However there is a new technique that I found very effective using display:inline-block property and mixing it with the container’s :before pseudo class.

Lets say we have a wrapper element

and contained element

which is needed to be vertically centered with a dynamic height. Below is the HTML & CSS:

HTML

 HTML |  copy code |? 
1
2
<div class="container">
3
<div class="element">
4
I am vertically centered
5
</div>
6
</div>
7

 CSS |  copy code |? 
01
02
.container:before{
03
content:'';
04
display:inlineblock;
05
width:0;
06
height:100%;
07
vertical−align:middle;
08
}
09
 
10
.element {
11
display:inlineblock;
12
vertical−align:middle;
13
}
14

DEMO

 

Related Post: How to remove whitespace from display:inline-block elements

No Comments

Post Your Comments

Name (required)
Email Address (will not be published) (required)