1

While using Material design responsive image I noticed even if I give fixed width to col, its size decreases as the container width decreases. I have breaked it down to a reproducible snippet:

.row {
  width: 80%;
  border: 1px dotted red;
  margin: 5px;
  display: flex;
}

.col {
  float: left;
}

.pic {
  width: 80px;
}

.pic img {
  max-width: 100%;
  height: auto;
}
<div class="row">
  <div class="col pic">
    <img src="https://s-media-cache-ak0.pinimg.com/236x/e1/38/a1/e138a174c33a48931521dcc5639d4a03--happy-pictures-smiley-faces.jpg" alt="">
  </div>
  <div class="col"> Resize the window to decrease it's width. When the text starts wrapping to second line the image starts shrinking</div>
</div>

jsfiddle: https://jsfiddle.net/2fbcggd8/

To see the problem try resizing the jsfiddle output section(right bottom). You'll notice the image which should be fixed 80px width decreases in size as the text wraps to second line. Why does this happen?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
user31782
  • 7,087
  • 14
  • 68
  • 143

2 Answers2

2

There are a number of ways to fix it, probably the simplest is just to add flex-shrink: 0 to .pic to keep it from shrinking. By default, it will shrink (initial value is flex-shrink: 1) https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink

You could also remove the width and use flex: 0 0 80px which is short hand for flex-grow: 0; flex-shrink: 0; flex-basis: 80px

.row {
  width: 80%;
  border: 1px dotted red;
  margin: 5px;
  display: flex;
}

.pic {
  width: 80px;
  flex-shrink: 0;
}

.pic img {
  max-width: 100%;
  height: auto;
}
<div class="row">
  <div class="col pic">
    <img src="https://s-media-cache-ak0.pinimg.com/236x/e1/38/a1/e138a174c33a48931521dcc5639d4a03--happy-pictures-smiley-faces.jpg" alt="">
  </div>
  <div class="col"> Resize the window to decrease it's width. When the text starts wrapping to second line the image starts shrinking</div>
</div>
Michael Coker
  • 52,626
  • 5
  • 64
  • 64
  • 1
    This pretty much covers it - https://stackoverflow.com/questions/34352140/what-are-the-differences-between-flex-basis-and-width – Paulie_D Jul 11 '17 at 14:42
2

Just add flex:1 0 80px; to get it. by default flex-shrink is 1 so if you assign it to 0 to get it.

.pic {
  /* width: 80px; */
  /* Remove it */
  flex: 1 0 80px;
}

.row {
  width: 80%;
  border: 1px dotted red;
  margin: 5px;
  display: flex;
}

.col {
  float: left;
}

.pic {
  /* width: 80px; */
  /* Remove it */
  flex: 1 0 80px;
}

.pic img {
  max-width: 100%;
  height: auto;
}
<div class="row">
  <div class="col pic">
    <img src="https://s-media-cache-ak0.pinimg.com/236x/e1/38/a1/e138a174c33a48931521dcc5639d4a03--happy-pictures-smiley-faces.jpg" alt="">
  </div>
  <div class="col"> Resize the window to decrease it's width. When the text starts wrapping to second line the image starts shrinking</div>
</div>

working fiddle

LKG
  • 4,152
  • 1
  • 11
  • 21