Home >Web Front-end >CSS Tutorial >How to Vertically Center a Div in CSS?
Vertically Centering a Div with margin:auto
While margin:O auto; horizontally centers a div, margin:auto auto; does not center it vertically. Unfortunately, vertical-align:middle; also doesn't work for block-level elements like divs.
Limitations:
Vertical Centering Workarounds:
Due to the nature of document flow and element height calculations, it's impossible to use margins for vertical centering within a parent element. These workarounds, however, can resolve the issue:
Nested Element Approach:
This requires nesting three elements as follows:
.container { display: table; height: 100%; position: absolute; overflow: hidden; width: 100%; } .helper { display: table-cell; vertical-align: middle; position: absolute; top: 50%; } .content { position: relative; top: -50%; margin: 0 auto; width: 200px; border: 1px solid orange; }
<div class="container"> <div class="helper"> <div class="content"> <p>stuff</p> </div> </div> </div>
The above is the detailed content of How to Vertically Center a Div in CSS?. For more information, please follow other related articles on the PHP Chinese website!