Vertical Alignment in CSS Using Percentage of Parent Container Height
In an effort to achieve vertical alignment in CSS, you had employed the following approach:
.base { background-color: green; width: 200px; height: 200px; overflow: auto; position: relative; } .vert-align { padding-top: 50%; height: 50%; }
While initially promising, this approach proved problematic when adjusting the width of the .base div, causing the vertical alignment to break. This behavior stems from the fact that padding-top is calculated as a percentage of the width instead of the height as expected.
Solution: Using Vertical Properties
To resolve this issue, you can leverage vertical CSS properties instead of padding-top. These properties are defined relative to the height of the parent element:
.base { background-color: green; width: 200px; height: 200px; overflow: auto; position: relative; } .vert-align { top: 50%; position: absolute; }
By setting top to 50%, you can effectively center the inner .vert-align div vertically within the .base container. This approach ensures that the vertical alignment remains intact regardless of the width of .base. Remember to set the position of the inner div to absolute for this to work correctly.
The above is the detailed content of How to Achieve Reliable Vertical Alignment in CSS Using Percentage Heights?. For more information, please follow other related articles on the PHP Chinese website!