Home >Web Front-end >CSS Tutorial >Why Doesn't `height: 100%` Work as Expected in Flexbox Columns in Chrome?

Why Doesn't `height: 100%` Work as Expected in Flexbox Columns in Chrome?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 22:03:02925browse

Why Doesn't `height: 100%` Work as Expected in Flexbox Columns in Chrome?

Height Problems in Flexbox Columns: A Chrome Quirk

In flexbox columns, you might encounter difficulties when using height percentages to size child elements. This issue stems from a quirk in Chrome's handling of the flexbox specification.

Consider the following example:

<div class='flexbox'>
  <div class='flex'>
    <div class='flex-child'></div>
  </div>
  <div class='static'></div>
</div>
.flexbox {
  position: absolute;
  background: black;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.flex {
  background: blue;
  flex: 1;
}

.flex-child {
  background: red;
  height: 100%;
  width: 100%;
  display: block;
}

.static {
  background: green;
  width: 100%;
  height: 5rem;
}

You would expect the red .flex-child element to occupy the entire height of its blue .flex parent. However, height:100% doesn't function as intended.

Solution:

To resolve this issue:

  1. Modify .flex to display: flex.
  2. Remove height:100% from .flex-child.

This adjustment ensures that .flex-child fills the entire space within .flex.

Technical Background:

In flexbox, align-self:stretch (the default) determines the cross-size property (here, height) of a flexed element. However, percentages use the specified cross-size value, not its used value. In this case, .flex-child tries to occupy 100% of .flex's specified height, which is auto by default. This confuses the layout engine.

Setting .flex to display: flex resolves the problem by overriding the default behavior and allowing the higher-level CSS to determine the sizing of .flex.

Exception:

This solution won't work if you want to partially fill .flex. To achieve this, you can add a .spacer element within .flex with flex:1 and set flex-child to flex:9 (and flex-direction:column on .flex). However, this is a hack and it's hoped that future browser updates will address this quirk.

The above is the detailed content of Why Doesn't `height: 100%` Work as Expected in Flexbox Columns in Chrome?. 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