belkka
belkka

Reputation: 273

Why is <img> width not updated properly inside flexbox?

There is a very weird behavior that I cannot explain:

Steps to reproduce:

  1. Create a flexbox container with non-empty <div> and <img> inside of it, set <img> width to absolute value, like 150px.
  2. Disable cache and enable network throttling in browser web inspector. Both these actions are required.
  3. Refresh the HTML document (or "Run" the JSFiddle)

Example

<div class="container">
  <div class="first">Text text text</div>
  <img class="second" src="https://i.sstatic.net/VmmrB.png">
</div>
.container {
  display: flex;
  border: 1px solid black;
}
.first {
  background: antiquewhite;
}
.second {
  width: 150px;
  height: 150px;
}

JSFiddle: https://jsfiddle.net/d6zes5yc/

Expected result:

Image width is equal to what is set in CSS, e. g. 150px

expected behavior

Actual result:

Image is shrunk...

actual behavior

...but it immediately updates the width if resize the window (!). Web inspector shows that its width does not correspond to the width set in CSS:

calculated width value

If I resize the document, or change browser tab and go back, image width changes to normal value (!). If this doesn't happen, I would think that I don't understand something in flexbox rules about how is flexbox elements width calculated. But the fact that browser displays document differently when I switch to another tab and go back looks very weird. Is it a bug in browsers? What is the explanation for this behavior?

Tested on:

In falkon 3.1.0 it works as expected

Note: declaring min-width/max-width with the same value as width or flex-shrink: 0 allows to "hide" the "problem". But a real problem is a lack of understanding why does this happen.

Upvotes: 4

Views: 390

Answers (1)

Yudiz Solutions
Yudiz Solutions

Reputation: 4449

Please try this code

.container {
  display: flex;
  border: 1px solid black;
}

.first {
  background: antiquewhite;
}

.second {
  width: 150px;
  height: 150px;
  flex-shrink: 0;
  -webkit-flex-shrink: 0;
}
<div class="container">
  <div class="first">
    Open "Network" tab in browser web inspector.
    Set "disable cache" and enable network throttling ("Fast 3G" works for me).
    Make viewport narrow enough; there must not be free space in flex container.
    Run the jsfiddle.
    See that image width is LESS then 150px.
    Resize the window a bit.
    See that image width become 150px now.
  </div>
  <img class="second" src="https://i.sstatic.net/VmmrB.png">
</div>

Upvotes: 1

Related Questions