Horizontally center div and content with pure CSS. There are 4 ways to do horizontally center any inner content or tags or elements between the outer tag by using position absolute, margin auto, text-align center, display flex, and transform properties.
HTML
<h2>First Way - Horizontally Center Div With Margin 0 Auto</h2>
<div class="first-way">
<div class="outerDiv">
<h3>Outer Div</h3>
<div class="innerDiv">Inner Div</div>
</div>
</div>
<h2>Second Way - Horizontally Center Div With Text Align Center</h2>
<div class="second-way">
<div class="outerDiv">
<h3>Outer Div</h3>
<div class="innerDiv">Inner Div</div>
</div>
</div>
<h2>Third Way - Horizontally Center Div With Position Absolute And Transform</h2>
<div class="third-way">
<div class="outerDiv">
<h3>Outer Div</h3>
<div class="innerDiv">Inner Div</div>
</div>
</div>
<h2>Fourth Way - Horizontally Center Div With Display Flex</h2>
<div class="fourth-way">
<div class="outerDiv">
<div class="innerDiv">Inner Div</div>
</div>
</div>
CSS
* {
box-sizing: border-box;
font-family: arial;
}
h2 {
text-align: center;
}
.outerDiv, .innerDiv {
border: 1px solid #ddd;
color: #E91E63;
padding: 30px;
position: relative;
background-color: #FAFAFA;
box-shadow: 0px 0px 7px 0px #dadada;
border-radius: 10px;
}
.outerDiv {
width: 90%;
margin: 0px auto 60px;
display: table;
}
/*-- First Way --*/
.first-way .innerDiv {
display: table;
margin: 0 auto;
}
/*-- Second Way --*/
.second-way .outerDiv {
text-align: center;
}
.second-way .innerDiv {
display: inline-block;
}
.second-way h3 {
text-align: left;
}
/*-- Third Way --*/
.third-way .innerDiv {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
/*-- Fourth Way --*/
.fourth-way .outerDiv {
display: flex;
justify-content: center;
}