Home > Web Front-end > CSS Tutorial > Why Does Percentage-Based Vertical Padding Fail, and How Can I Use Percentage Heights for Vertical Alignment in CSS?

Why Does Percentage-Based Vertical Padding Fail, and How Can I Use Percentage Heights for Vertical Alignment in CSS?

Mary-Kate Olsen
Release: 2024-12-11 20:17:15
Original
460 people have browsed it

Why Does Percentage-Based Vertical Padding Fail, and How Can I Use Percentage Heights for Vertical Alignment in CSS?

How to Control Padding and Margin Using Percentage of Parent Container Height

In CSS, controlling vertical alignment can be achieved using the padding-top property. However, setting this property as a percentage of the parent container's width instead of height can lead to undesirable behavior.

Original Attempt:

.base {
  background-color: green;
  width: 200px;
  height: 200px;
  overflow: auto;
  position: relative;
}

.vert-align {
  padding-top: 50%;
  height: 50%;
}
Copy after login

Unexpected Behavior:

When changing the width of the .base container, the vertical alignment snapped, even though padding-top was set as a percentage. This is because vertical padding and margin are calculated as a percentage of the parent container's width.

Solution:

Instead of using padding-top, use the top property to control vertical alignment. top is calculated as a percentage of the parent container's height.

.base {
  background-color: green;
  width: 200px;
  height: 200px;
  overflow: auto;
  position: relative;
}

.vert-align {
  position: absolute;
  top: 50%;
}
Copy after login

This nested div structure places a child div inside the parent container and aligns it vertically:

<div class="base">
  <div class="vert-align">
    Content Here
  </div>
</div>
Copy after login

By using top instead of padding-top, the child div is positioned 50% down from the top of its parent container, regardless of its width. This ensures vertical alignment even when the parent's width changes.

The above is the detailed content of Why Does Percentage-Based Vertical Padding Fail, and How Can I Use Percentage Heights for Vertical Alignment in CSS?. 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