Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

html - Flex in Firefox shrinks images automatically, but not in Chrome

<h1>Window width:</h1>

<div style="display: flex">
  <img src="https://unsplash.it/400/225?image=10" alt="1">
  <img src="https://unsplash.it/400/225?image=11" alt="2">
  <img src="https://unsplash.it/400/225?image=12" alt="3">
</div>

<h1>Wrapped in 500px wide div:</h1>

<div style="width: 500px; overflow: auto">
  <div style="display: flex">
    <img src="https://unsplash.it/400/225?image=10" alt="1">
    <img src="https://unsplash.it/400/225?image=11" alt="2">
    <img src="https://unsplash.it/400/225?image=12" alt="3">
  </div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

These are initial settings in a flex container:

  • flex-grow: 0
  • flex-shrink: 1
  • flex-basis: auto

The shorthand would be:

  • flex: 0 1 auto

Therefore, even though you haven't specified these rules in your code, they apply to the images.

The images cannot grow, they can shrink (equally and just enough to avoid overflowing the container), and they are initially sized to their natural width (400px).

This is what you're seeing in Firefox. The images are shrinking to fit nicely within the container.

In Firefox, flex rules are overriding the natural dimensions of the image.

In Chrome, however, the reverse is true. The dimensions of the images are prevailing.

The simple cross-browser solution is to wrap the images in another element, so this new wrapper becomes the flex item and takes on the default flex: 0 1 auto, and nothing needs to be overridden.

img {
  width: 100%;
}
<h1>Window width:</h1>

<div style="display: flex">
  <span><img src="https://unsplash.it/400/225?image=10" alt="1"></span>
  <span><img src="https://unsplash.it/400/225?image=11" alt="2"></span>
  <span><img src="https://unsplash.it/400/225?image=12" alt="3"></span>
</div>

<h1>Wrapped in 500px wide div:</h1>

<div style="width: 500px; overflow: auto">
  <div style="display: flex">
    <span><img src="https://unsplash.it/400/225?image=10" alt="1"></span>
    <span><img src="https://unsplash.it/400/225?image=11" alt="2"></span>
    <span><img src="https://unsplash.it/400/225?image=12" alt="3"></span>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...