Home > Web Front-end > CSS Tutorial > How to Make a Flexbox Child Element Fill 100% of its Parent's Height?

How to Make a Flexbox Child Element Fill 100% of its Parent's Height?

Mary-Kate Olsen
Release: 2024-12-19 16:00:14
Original
502 people have browsed it

How to Make a Flexbox Child Element Fill 100% of its Parent's Height?

Flexbox Child Height: Achieving 100% Parent Fill

In the world of Flexbox, filling the vertical space of child elements poses a common challenge. Let's consider the code snippet you provided:

.container {
  height: 200px;
  width: 500px;
  display: flex;
  flex-direction: row;
}
.flex-1 {
  width: 100px;
  background-color: blue;
}
.flex-2 {
  position: relative;
  flex: 1;
  background-color: red;
}
.flex-2-child {
  height: 100%;
  width: 100%;
  background-color: green;
}
Copy after login

In this scenario, the flex-2-child element fails to occupy the full vertical space of its parent container, except when flex-2 has a height of 100% or when flex-2-child has an absolute position. However, both solutions come with their own drawbacks.

The Solution: Align-Items Stretch

One effective workaround involves employing the align-items property on the parent container (flex-2):

.flex-2 {
    display: flex;
    align-items: stretch;
}
Copy after login

Note that the height: 100%; property should be removed from the child component (flex-2-child).

This approach instructs the flex-2-child element to stretch vertically, filling the available space within its parent container. It works in both Chrome and Firefox.

As an alternative to align-items, you can apply align-self specifically to the flex-2-child element you want to stretch:

.flex-2-child {
    align-self: stretch;
}
Copy after login

By utilizing either technique, you can achieve the desired behavior of having Flexbox children fill the full height of their parent elements.

The above is the detailed content of How to Make a Flexbox Child Element Fill 100% of its Parent's Height?. 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