Using Flexbox To Fill The Remaining Space In An Element

June 25, 2018 by David Ugale

Using a Flexbox layout is a great way to fill the available space in an element. For example, say you have a thumbnail and a description that you want to have fill up all of the available horizontal space. The thumbnail will be aligned to the left and will take up a width of 120 pixels. However, the description needs to fill up the remaining space in the parent element and that width can vary depending on the size of the browser window. The solution is to use flex.

Here is an example:

Variable Width Element
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum erat erat, molestie eu elit eu, elementum eleifend magna. Curabitur at ultricies sapien. Praesent a massa congue, bibendum sapien id, gravida sem. Donec vestibulum elit sit amet nibh accumsan euismod. Integer tellus urna, ornare sed nulla sed, pellentesque maximus enim. Pellentesque turpis magna, tempus sit amet ornare a, mollis et odio.

HTML


<div id="flex-container">
<div id="flex-fixed-width">
<strong>Fixed Width Element</strong><div>
<div id="flex-variable-width">
<strong>Variable Width Element</strong><br>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum erat erat, molestie eu elit eu, elementum eleifend magna. Curabitur at ultricies sapien. Praesent a massa congue, bibendum sapien id, gravida sem. Donec vestibulum elit sit amet nibh accumsan euismod. Integer tellus urna, ornare sed nulla sed, pellentesque maximus enim. Pellentesque turpis magna, tempus sit amet ornare a, mollis et odio.
</div>
</div>

CSS


#flex-container {
    border: solid red 5px;
    display: flex; /* parent element has a flexbox layout */
}
#flex-fixed-width {
    flex: 0 0 120px; /* fixed width element set to 120px width */
    padding: 10px;
}
#flex-variable-width {
    /* no flex property has to be set */
    padding: 10px;
}