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