Another way (not mentioned here yet) is with Flexbox.
Just add the following code to the container element:
display: flex;
justify-content: center; /* Align horizontal */
align-items: center; /* Align vertical */
.box {
height: 150px;
width: 400px;
background: #000;
font-size: 24px;
font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center;
/* align horizontal */
align-items: center;
/* align vertical */
}
<div class="box">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
</div>
Alternatively, instead of aligning the content via the container, flexbox can also center a flex item with an auto margin when there is only one flex-item in the flex container (like the example given in the question above).
So to center the flex item both horizontally and vertically just set it with margin:auto
.box {
height: 150px;
width: 400px;
background: #000;
font-size: 24px;
font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
}
.box span {
margin: auto;
}
<div class="box">
<span>margin:auto on a flex item centers it both horizontally and vertically</span>
</div>
NB: All the above applies to centering items while laying them out in horizontal rows. This is also the default behavior, because by default the value for flex-direction
is row
. If, however flex-items need to be laid out in vertical columns, then flex-direction: column
should be set on the container to set the main-axis as column and additionally the justify-content
and align-items
properties now work the other way around with justify-content: center
centering vertically and align-items: center
centering horizontally)
.box {
height: 150px;
width: 400px;
background: #000;
font-size: 18px;
font-style: oblique;
color: #FFF;
display: flex;
flex-direction: column;
justify-content: center;
/* vertically aligns items */
align-items: center;
/* horizontally aligns items */
}
p {
margin: 5px;
}
<div class="box">
<p>
When flex-direction is column...
</p>
<p>
"justify-content: center" - vertically aligns
</p>
<p>
"align-items: center" - horizontally aligns
</p>
</div>
A good place to start with Flexbox to see some of its features and get syntax for maximum browser support is flexyboxes
Also, browser support nowadays is very good: caniuse
For cross-browser compatibility for display: flex
and align-items
, you can use the following:
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;