Using CSS flex to Fill Remaining Space in an Element

David Ugale, Author
Written by David Ugale

Using a flexbox layout is a great way to fill the available space in an element.

For example, you could use a flexbox layout when you have a thumbnail image and want the text description to fill the remaining width of the containing element. 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 the css flex property.

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">
    <img src="/wp-content/uploads/2018/06/fixed-width-element-1200.jpg" alt="" width="100" height="100" />
  <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;
  /* parent element has a flexbox layout */
  display: flex; 
}
#flex-fixed-width {
  /* fixed width element set to 120px width */
  flex: 0 0 120px;
  padding: 10px;
}
#flex-variable-width {
  /* css flex will fill remaining extra space */
  padding: 10px;
}
Originally published June 25th, 2018, updated November 4th, 2022