Prevent image from shrinking with Flexbox

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.

  1. <div class="container">
  2. <div class="image">
  3. <img src="http://placehold.it/100x100" width="100" height="100" />
  4. </div>
  5. <div class="info">
  6. <p>Temporibus luctus inventore! Ornare adipisicing occaecati sunt leo optio porta rhoncus venenatis illum, consequat vulputate, ab. Tenetur velit porta pariatur.</p>
  7. </div>
  8. </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:

  1. .container {
  2. display: flex;
  3. }

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%:

  1. img {
  2. width: 100%;
  3. }

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.

  1. img {
  2. width: 100%;
  3. }
  4.  
  5. .image {
  6. flex-shrink: 0;
  7. }

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!

Enjoy this article?

Get my best content on Javascript, CSS, PHP & Git before anyone else and special bonuses.

Get started

Comments

Hi Blair,

Thank you for this awesome post. I was fighting hard with a html widget I had which had text alignment issue due to left thumbnail shrinking on different sizes. I controlled this property , thanks to your post, and it gave me the control I needed to fix the alignment issue. Thank you again for your time and posting this!

Blair Wadman's picture

Glad it helped Mohsin!

Add new comment