Home > Web Front-end > CSS Tutorial > How to Achieve Reliable Vertical Alignment in CSS Using Percentage Heights?

How to Achieve Reliable Vertical Alignment in CSS Using Percentage Heights?

Patricia Arquette
Release: 2024-12-08 10:12:13
Original
324 people have browsed it

How to Achieve Reliable Vertical Alignment in CSS Using Percentage Heights?

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%;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template