My prefered way to center a box both vertically and horizontally, is the following technique :
The outer container
- should have
display: table;
The inner container
- should have
display: table-cell;
- should have
vertical-align: middle;
- should have
text-align: center;
The content box
- should have
display: inline-block;
- should re-adjust the horizontal text-alignment to eg.
text-align: left;
or text-align: right;
, unless you want text to be centered
The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
Demo
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>
See also this Fiddle!
EDIT
Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%);
or transform: translate3d(-50%,-50%, 0);
, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit
, -ms
or -moz
, transform
doesn't offer quite the same browser support.
So if you care about older browsers (eg. IE9 and below), you should not use transform
for positioning.