Home >Web Front-end >CSS Tutorial >Why Doesn't `height: 100%` Work on a Child Element When the Parent Only Has `min-height`?

Why Doesn't `height: 100%` Work on a Child Element When the Parent Only Has `min-height`?

Susan Sarandon
Susan SarandonOriginal
2024-12-26 09:13:15480browse

Why Doesn't `height: 100%` Work on a Child Element When the Parent Only Has `min-height`?

Why Child Height Fails Despite 100% When Parent Has Only min-height/max-height

In the given HTML snippet, the parent container element with min-height: 300px and no explicit height value causes the child element's height: 100% to fail.

Understanding the Behavior

According to the CSS specification:

"Specifies a percentage height. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto.'"

In the provided scenario, the container element's height is not explicitly defined. Instead, it's determined based on its content and the min-height value. As a result, the child element's height: 100% cannot be calculated accurately.

Requiring an Explicit Height

When a height value is set on the container, even as small as 1px, it explicitly defines the height of the containing block. This allows the child element's height: 100% to calculate and apply correctly, filling the entire container even without explicit height set.

Alternative Approach

If the desired behavior is for the child element to fill the entire parent element regardless of the parent's height, one alternative approach is to use CSS flexbox like:

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.child {
  height: 100%;
}

The above is the detailed content of Why Doesn't `height: 100%` Work on a Child Element When the Parent Only Has `min-height`?. 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