Explanation
Change the CSS property position
of the wrapper to relative and of element you want centered to absolute.
Then position the element in the middle of the wrapper using top: 50%
and left: 50%
.
After this you will notice that the element is not exactly centered, because it's own height and width are off the calculation.
So we fix with the property transform: translate(-50%, -50%)
, which brings the element half of it's height up, and half it's width left. The result will be a vertically and horizontally centered element.
Since we are taking IE8 into consideration, we will use a filter
to achieve the same effect as the transform: translate
.
In order to generate the filter
attribute, the following resource was used: IE's CSS3 Transforms Translator
Example
.box {
margin: 10px;
display: inline-block;
position: relative;
}
.box span {
position: absolute;
top: 50%;
left: 50%;
background: #fff;
box-shadow: 0 0 3px rgba(0, 0, 0, 1);
padding: 5px;
}
.box.translate > span {
transform: translate(-50%, -50%);
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod='auto expand')";
}
<div class="box translate">
<img src="http://placehold.it/500x200" />
<span>centered text</span>
</div>