Question:
Is it possible to center a DIV vertically using margin:auto auto;? Why doesn't vertical-align:middle; work?
Answer:
Regarding Margin:
Unfortunately, margin:auto auto; does not achieve vertical centering. Margins are not applicable to block-level elements like DIVs for vertical alignment. As a result, margin:top:auto and margin-bottom:auto are ineffective.
Regarding vertical-align:middle;:
vertical-align:middle; is only applicable to inline elements, not block-level elements like DIVs.
Workaround:
Since it's not possible to vertically center a DIV using margins, a workaround solution is recommended. One approach that works well is to use nested elements within a table-like container:
.container { display: table; height: 100%; position: absolute; overflow: hidden; width: 100%; } .helper { position: absolute; top: 50%; display: table-cell; vertical-align: middle; } .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 Can I Vertically Center a DIV Using `margin: auto`?. For more information, please follow other related articles on the PHP Chinese website!