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.
<html>
<head>
<style>
.container {
display: flex;
width: 100%;
}
.fixed-width {
width: 200px;
background-color: lightcoral;
padding: 10px;
text-align: center;
}
.fill-space {
flex: 1;
background-color: lightblue;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="fixed-width">Fixed Width</div>
<div class="fill-space">Fills Remaining Space</div>
</div>
</body>
</html>
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.
<html>
<head>
<style>
.container {
width: 100%;
display: flex;
}
.fixed-width {
width: 250px;
background-color: lightgreen;
padding: 10px;
text-align: center;
}
.fill-space {
width: calc(100% - 250px);
background-color: lightgoldenrodyellow;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<div class="fixed-width">Fixed Width</div>
<div class="fill-space">Fills Remaining Space</div>
</div>
</body>
</html>
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.
<html>
<head>
<style>
.fixed-width {
float: left;
width: 150px;
background-color: lightgreen;
padding: 10px;
text-align: center;
}
.fill-space {
overflow: hidden;
background-color: lightpink;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="fixed-width">Fixed Width</div>
<div class="fill-space">Fills Remaining Space</div>
</body>
</html>
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.