How To Make HTML Element Fill Remaining Space

CSS

30/08/2021


The best way to approach this problem is by using Flexbox. Take this div container with two child elements:

HTML
<div class="container">
<div>1</div>
<div>2</div>
</div>

It has the following CSS applied where the first child has a fixed width.

CSS
.container {
display: flex;
width: 100%;
border: 1px solid;
color: white;
}
.container > div:first-child {
background-color: red;
width: 100px;
}
.container > div:last-child {
background-color: blue;
}

Parent container with 2 child elements

Parent container with 2 child elements

By adding a flex property to the 2nd child, we can make it fill up the remaining space in the parent container.

DIFF
.container > div:last-child {
background-color: blue;
+ flex: 1;
}

Child element filling up remaining space

2nd child filling up remaining space

WRITTEN BY

Code and stuff