Here are three methods to make a div fill the remaining horizontal space using CSS:
1. Using Flexbox
Flexbox is a layout model that makes it easy to distribute space and align items within a container. It automatically allows a div to fill the available space flexibly.
In this Example:
- The .container is set to display: flex;, enabling a flexible layout where child elements can adjust dynamically.
- The .fill-space div uses flex: 1; to expand and fill the remaining horizontal space, while the .fixed-width div maintains a fixed width of 200px.
2. Using calc() with CSS Width
The calc() function can dynamically calculate the remaining space by subtracting the width of other elements from the total width.
In this Example:
- The .container is styled with display: flex; to enable a flexible layout.
- The .fixed-width div has a fixed width of 250px, while the .fill-space div uses width: calc(100% - 250px); to occupy the remaining horizontal space dynamically.
3. Using Float and Overflow
This method employs the float property for the fixed-width element and overflow: hidden; for the adjacent element to occupy the remaining horizontal space.
In this Example:
- The .fixed-width div is floated to the left with a set width of 150px, allowing subsequent content to flow alongside it.
- The .fill-space div, with overflow: hidden;, occupies the remaining horizontal space next to the floated element, effectively preventing content overflow and ensuring proper layout.