Flexbox is a very powerful CSS layout module that allows flexible control over layout. However, specifying height: 100%;
on a Flexbox child element may not work as expected. This problem is related to the characteristics of Flexbox and the CSS rules for calculating height. This article details the cause of this problem and how to resolve it.
Cause of the Problem
When using Flexbox, height: 100%;
does not work as expected because the height of the Flexbox container (parent element) is not clearly defined. If the height of the parent element is not clear, the child element will not be able to set its height to 100%. This is the root cause of the problem.
Solution
Below are several ways to resolve the issue of height: 100%;
not working on Flexbox child elements.
Method 1: Set the height on the parent element
Specifying an explicit height for the parent element will allow the height: 100%;
on the child elements to work correctly. The following code example sets the parent element to height: 100vh;
(100% of the viewport height).
<style>
.parent {
display: flex;
height: 100vh;
}
.child {
height: 100%;
background-color: #f0f0f0;
}
</style>
<div class="parent">
<div class="child">child element</div>
</div>
Description: By setting the height of the parent element, the child elements will have a height of 100% to match its height.
Method 2: Automatically adjust the height using Flexbox properties
You can use Flexbox’s align-items: stretch; property
to automatically match the height of a child element to the height of its parent element. This is the default setting, but it assumes that the parent element’s height is set.
<style>
.parent {
display: flex;
height: 100vh;
align-items: stretch;
}
.child {
background-color: #d0d0d0;
}
</style>
<div class="parent">
<div class="child">element1</div>
<div class="child">element2</div>
</div>
Description: When align-items: stretch;
is set, child elements automatically adapt to the height of the parent element. This method is especially useful when the height of the parent element is variable.
Method 3: Set min-height on the Flexbox container
Specifying min-height on
the parent element also allows the child element’s height: 100%;
to function properly. This will ensure that the parent element does not have a height of zero.
<style>
.parent {
display: flex;
min-height: 300px;
}
.child {
height: 100%;
background-color: #e0e0e0;
}
</style>
<div class="parent">
<div class="child">element</div>
</div>
Explanation: min-height
can be used to prevent the parent element from having a height of zero and allow the child element’s height: 100%;
to work.
Conclusion
Problems with height: 100%;
not working on Flexbox child elements are often caused by the height setting of the parent element. Proper height settings and Flexbox properties can solve this problem; understanding the properties of Flexbox and making the appropriate settings will allow for maximum design flexibility.