Flexbox is a relatively new CSS mode that makes it a lot easier to create awesome layouts. One of the features of the Flexbox model is that elements in a single row will shrink in size as the amount of available space is reduced. For example, if you have a row of elements and you decrease the width of the browser, the elements will shrink in width as the width of the containing element reduces. This is necessary in order to keep the elements on a single row.

If the row contains an image, you have two options:

  • Allow it to shrink along with the other elements
  • Keep it a fixed size and still allow the other elements to shrink.

Let’s have look at how you can do both of these options.

The base code

In this simple example, we have a div which contains an image and info text.

<div class="container">
  <div class="image">
     <img src="http://placehold.it/100x100" width="100" height="100" />
  </div>
  <div class="info">
    <p>Temporibus luctus inventore! Ornare adipisicing occaecati sunt leo optio porta rhoncus venenatis illum, consequat vulputate, ab. Tenetur velit porta pariatur.</p>
  </div>
</div>

We want the image and text to sit side by side in a single row. All you need to do is to set the display of the container to flex:

.container {
    display: flex;
} 

You don’t need to worry about floats. Thanks to the magic of flexbox!

1. Allow it to shrink

To ensure the image shrinks when the available space is reduced, simply set the with of img to 100%:

img {
  width: 100%;
}

2. Fixed size

If you remove the 100% width above, then the image should retain its normal size even when the available space is reduced. However, if you want to keep the 100% img for any reason, then you need to add the flex-shrink property to the element containing the image and give it a value of 0.

img {
  width: 100%;
}
 
.image {
    flex-shrink: 0;
}

Here is the full code in action:

See the Pen GJZpmM by Blair Wadman (@blairwadman) on CodePen.

And that is all there is to it!