Search code examples
htmlcssflexboxresponsive-images

Picture element WebP flexing


Background: Bootstrap 3 way of laying out 8 images in a row

I now know how to flex 3 images:

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-content: space-around;
  align-items: flex-start;
}
img {
  width: 30%;
  order: 0;
  flex: 0 1 auto;
  align-self: auto;
}
<img src="https://placehold.it/1024x768" />
<img src="https://placehold.it/1024x768" />
<img src="https://placehold.it/1024x768" />

But I want to introduce smaller WebP alternative images and I think you do that with the picture element.

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  align-content: space-around;
  align-items: flex-start;
}
picture {
  width: 30%;
  order: 0;
  flex: 0 1 auto;
  align-self: auto;
}
<picture>
  <source srcset="http://s.natalian.org/2015-12-12/1024x768.webp" type="image/webp" />
  <img src="https://placehold.it/1024x768" />
</picture>

<picture>
  <source srcset="http://s.natalian.org/2015-12-12/1024x768.webp" type="image/webp" />
  <img src="https://placehold.it/1024x768" />
</picture>

<picture>
  <source srcset="http://s.natalian.org/2015-12-12/1024x768.webp" type="image/webp" />
  <img src="https://placehold.it/1024x768" />
</picture>

However, I can't figure out how to make the CSS format the PICTUREs 3 abreast like they do with IMG. What am I missing?


Solution

  • When you create a flex container only the child elements become flex items. Descendants beyond the children do not become flex items and flex properties don't apply to them.

    In your first example, body is the flex container and img is the flex item.

    In your second example, however, body is the flex container, picture is the flex item, and img is, well, nothing special in terms of flex. It's a normal inline element.

    You'll need to make picture a (nested) flex container in order to apply flex properties to the image elements. But in your case, this may not be necessary.

    Also note that the picture element is not universally supported yet (see caniuse.com).

    Your first demo: DEMO 1

    Your second demo, revised: DEMO 2