Keywords: CSS | vertical space | position:absolute | web layout | HTML
Abstract: This article explores a pure CSS solution to fill the remaining vertical space in a container using the position:absolute property. It covers implementation, code examples, and comparisons with alternative methods like Flexbox, aimed at front-end developers.
In web development, a common requirement is to have a div element fill the remaining vertical space after another fixed-height div. This article focuses on a solution based on the CSS position:absolute property, which is simple and effective for various layout scenarios.
Core Method: position:absolute
To fill remaining space using position:absolute, first set the parent container to position:relative to establish a positioning context. Then, set the target child element to position:absolute and dynamically adjust its height by specifying top and bottom properties. For example, if the first div has a height of 200px, the second div's top should be set to 200px and bottom to 0, allowing it to stretch and fill the remaining space.
#wrapper {
position: relative;
width: 300px;
height: 100%;
}
#second {
position: absolute;
top: 200px; /* corresponds to the height of #first */
bottom: 0;
left: 0;
width: 300px;
background-color: #9ACD32;
}The key to this method is leveraging absolutely positioned elements that are removed from the normal document flow, with top and bottom values defining their vertical range. Ensure the parent container has a defined height (e.g., height: 100%) to avoid layout issues.
Alternative Methods: Flexbox
Beyond position:absolute, CSS Flexbox is a powerful layout tool, especially for dynamic content. By setting the parent container to display: flex and flex-direction: column, child elements can use the flex-grow property to distribute remaining space. For instance, the second div can be set to flex-grow: 1 to fill the space.
.wrapper {
display: flex;
flex-direction: column;
height: 100%;
width: 300px;
}
.second {
flex-grow: 1;
background-color: #9ACD32;
}The Flexbox method is more modern and supports responsive design, but browser compatibility may require prefixes or polyfills for older versions.
Comparison and Conclusion
The position:absolute method is suitable for simple, fixed layouts, offering concise code and good compatibility. In contrast, Flexbox provides greater flexibility for complex or dynamic content. Developers should choose based on project requirements, browser support goals, and code maintainability. In practice, combining these techniques can effectively address vertical space filling challenges.