This is a simple demo of a “masonry” style effect for images using flexbox. The markup is very straightforward:
<div id="masonry">
<img src="irina.jpg" alt>
<img src="daniella.jpg" alt>
<img src="karina.jpg" alt>
…
</div>
The CSS is also remarkably easy. I have not used vendor prefixes for Firefox or Chrome in the stylesheet, as both have been prefix-free for flexbox for some time:
div#masonry {
display: -ms-flexbox;
-ms-flex-direction: column;
-ms-flex-wrap: wrap;
display: flex;
flex-direction: column;
flex-wrap: wrap;
height: 100vw;
font-size: 0;
}
div#masonry img {
width: 33.3%;
transition: .8s opacity;
}
div#masonry:hover img {
opacity: 0.3;
}
div#masonry:hover img:hover {
opacity: 1;
}
The important part to note at this point is the height
on the containing <div>
: without this limit, the images will continue in a single unbroken vertical column, ignoring the flex-wrap
property.
Fallbacks
For older browsers, I’ve added one more rule at the bottom of the stylesheet:
@supports not (flex-wrap: wrap) {
div#masonry {
display: block;
}
div#masonry img {
display: inline-block;
vertical-align: top;
}
}
Part of the Feature Queries module, the @supports
rule allows a site to interrogate the browser as to which CSS properties and features it supports, just as @media
queries allow us to ask about viewport size, height and resolution. Over time, @supports
queries will allow us to create pure CSS fallbacks in browsers, replacing many JavaScript feature detection scripts and polyfills.
Right now, @supports
is only understood in Firefox, Chrome, and the latest version of Android browser (4.4, as of this writing). That’s okay: IE10 is covered in the CSS above, and IE9 and earlier would be addressed in a separate conditional comment. But earlier versions of Firefox present a problem: they support display: flex
but not flex-wrap
, leading to a visual equivalent to Frankenstein’s monster.
code>display: inline-block for images is not exactly the same as flexbox – occasional vertical gaps appear between the columnar images – but it’s a decent fallback.
Mobile Affordances
Reverting to two-column layout on mobile to preserve image quality is very easy:
@media screen and (max-width: 500px) {
div#masonry { height: 200vw; }
div#masonry img { width: 50%; }
}
Conclusion
As you can see, flexbox now allows us to create masonry and Pinterest-style layouts with ease. There’s a great deal more that can be done with wrapped flexbox items, as I’ll show in the very near future.
Photographs by Sean Archer, licensed under Creative Commons
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.
Check out the CodePen demo for this article at https://codepen.io/dudleystorey/pen/eAqzk