The Holy Grail of CSS Centering
Chris Coyier recently published a decision tree on his site, CSS Tricks, to demonstrate a plethora of ways to horizontally or vertically center things using CSS. As standalone solutions they all have their caveats, but combined they're an unstoppable centering tool which works cross-browser in IE8 and up consistently.
This is how you do it.
Note: to cover all bases I've provided the explanation in video and written form.
Watch the Video
Download video or subscribe to Tuts+ Web Design on Youtube
Read the Tutorial
If you're making a responsive website, you'll most likely be sizing your elements with percentages, so let's make an arbitrary .container
element:
1 |
<div class="container"> |
2 |
... |
3 |
</div>
|
1 |
.container { |
2 |
width: 70%; |
3 |
height: 70%; |
4 |
margin: 40px auto; |
5 |
background: red; |
6 |
}
|
To make sure our containing element stretches out appropriately, let's set html, body { width: 100%; height: 100%; }
.
Turning the Tables
Now, inside that .container
, we're going to get vertical centering with the common table pattern. This takes normal block level elements and makes them behave like table cells, giving us vertical centering:
1 |
<div class="container"> |
2 |
<div class="outer"> |
3 |
<div class="inner"> |
4 |
... |
5 |
</div>
|
6 |
</div>
|
7 |
</div>
|
1 |
.outer { |
2 |
display: table; |
3 |
width: 100%; |
4 |
height: 100%; |
5 |
}
|
6 |
.inner { |
7 |
display: table-cell; |
8 |
vertical-align: middle; |
9 |
text-align: center; |
10 |
}
|
Finally, we are going to add a horizontally centered element:
1 |
<div class="container"> |
2 |
<div class="outer"> |
3 |
<div class="inner"> |
4 |
<div class="centered"> |
5 |
... |
6 |
</div>
|
7 |
</div>
|
8 |
</div>
|
9 |
</div>
|
1 |
.centered { |
2 |
position: relative; |
3 |
display: inline-block; |
4 |
|
5 |
width: 50%; |
6 |
padding: 1em; |
7 |
background: orange; |
8 |
color: white; |
9 |
}
|
Inside of that, you can place anything your heart desires, including dynamic height text blocks, or absolutely positioned elements.
Alterations
To change the horizontal centering of the element, just modify .inner
's text-align
property. To change the vertical centering, modify .inner
's vertical-align
property.
In Conclusion
This example may seem like a lot of markup, but the working pieces are just three div
s: .outer
, .inner
, and.centered
. And the styling for these is consistent so you can use this in your boilerplate CSS across projects and never worry about it again.
It's one more element larger than most centering techniques and completely bulletproof. My hope is that this becomes the standard approach and we can finally stop worrying about centering in CSS.