Vertical Alignment of Content within Defined Div Dimensions
Centering content vertically within a div of a specified width and height can be achieved through various methods. Let's explore some popular options:
1. Display: Table-Cell for Parent Div
Setting the parent div's display to table-cell and using vertical-align: middle on the child content allows for vertical centering.
.parent-div { display: table-cell; vertical-align: middle; }
2. Display: Block and Display: Table-Cell
Setting the parent div's display to block and the child content's display to table-cell achieves similar results.
.parent-div { display: block; text-align: center; } .child-content { display: table-cell; vertical-align: middle; }
3. Floating Parent Div and Display: Table-Cell
Floating the parent div and setting the child content's display to table-cell also results in vertical centering.
.parent-div { float: left; text-align: center; } .child-content { display: table-cell; vertical-align: middle; }
4. Position: Relative and Position: Absolute
By setting the parent div's position to relative and the child content's position to absolute, top to 50%, and margin-top to -50%, vertical centering can be achieved. However, this method requires manual adjustments for different height scenarios.
.parent-div { position: relative; height: 100px; width: 100px; } .child-content { position: absolute; top: 50%; margin-top: -50%; width: 100px; }
The above is the detailed content of How to Vertically Center Content Within a Div?. For more information, please follow other related articles on the PHP Chinese website!