Home > Web Front-end > CSS Tutorial > Why Doesn't Percentage Height Work as Expected in Flexbox Columns?

Why Doesn't Percentage Height Work as Expected in Flexbox Columns?

Mary-Kate Olsen
Release: 2024-11-09 00:06:02
Original
388 people have browsed it

Why Doesn't Percentage Height Work as Expected in Flexbox Columns?

Percentage Height Issues in Flexbox Columns

In flexbox layouts, it's often desired to have children of a flexbox column fill their height. However, users may encounter issues where setting the height to percentages does not yield the expected result.

Explanation

According to the flexbox specification, an element's cross-size property (height, in this case) uses a specified value and a used value. Percentage heights are calculated based on the specified height of the parent, not the used height.

Solution

To address this issue in Chrome:

  1. Set the parent container (.flex) to display: flex.
  2. Remove the height: 100%; rule from the child element (.flex-child).

Example:

.flexbox {
  position: absolute;
  background: black;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.flex {
  background: blue;
  flex: 1;
  display: flex; /* Added */
}

.flex-child {
  background: red;
  width: 100%; /* Removed height: 100%; */
  display: block;
}
Copy after login

Alternative Approach for Partial Filling

In cases where filling only a portion of the parent container is desired, an additional flex child (.spacer) can be added to take up the remaining space.

.flex-child {
  flex: 9;
}

.spacer {
  flex: 1;
}
Copy after login

Conclusion

By understanding the difference between specified and used values, developers can overcome percentage height issues in flexbox columns. Though a browser-specific workaround may be necessary in some cases, it is expected that specification updates will address these limitations in the future.

The above is the detailed content of Why Doesn't Percentage Height Work as Expected in Flexbox Columns?. 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