Home > Article > Web Front-end > How to center a div?
Centering a div is the most impossible thing
Flexbox is a modern way to center content both vertically and horizontally:
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
CSS Grid can also center content:
.container { display: grid; place-items: center; height: 100vh; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
You can center a div using absolute positioning:
.container { position: relative; height: 100vh; } .centered-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
For simple horizontal centering, use margin: auto:
.centered-div { width: 50%; margin: 0 auto; }
<div class="centered-div">Centered Content</div>
For inline or inline-block elements:
.container { text-align: center; line-height: 100vh; } .centered-div { display: inline-block; vertical-align: middle; line-height: normal; }
<div class="container"> <div class="centered-div">Centered Content</div> </div>
The above is the detailed content of How to center a div?. For more information, please follow other related articles on the PHP Chinese website!