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
Mary-Kate OlsenOriginal
2024-12-11 20:17:15456browse

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%;
}

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%;
}

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>

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!

Statement:
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