Centering a Div Vertically within a Parent Div
Vertically centering a div within its parent div can be achieved through various methods, without relying on specific element dimensions.
Table Layout (Classic Approach)
This method utilizes table layout and inline-block display properties.
<div class="container"> <div class="inner"> ... </div> </div>
.container { display: table-cell; vertical-align: middle; height: 500px; width: 500px; } .inner { display: inline-block; width: 200px; height: 200px; }
Transform (Modern Approach)
Transformations offer a simpler solution for vertical centering.
.container { position: relative; height: 500px; width: 500px; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; }
Flexbox (Preferred Modern Approach)
Flexbox provides the most straightforward method for centered alignment.
.container { display: flex; justify-content: center; align-items: center; height: 500px; width: 500px; } .inner { width: 200px; height: 200px; }
Note:
The above is the detailed content of How to Vertically Center a Div within its Parent Div?. For more information, please follow other related articles on the PHP Chinese website!