Feb 20,2017 at 05:16 pm

CSS3/HTML5 Masonry Effect

The masonry layout, made famous by Pinterest, is a column based grid that neatly organizes div elements on a page. In many cases, the unique layout is achieved with a jquery plugin, which is easy to install and setup. Today, we're going to talk about achieving a masonry layout without jquery. The code is very simple:

masonry {
-moz-column-count: 3; /* how many columns do you want on your page? /
-moz-column-gap: 10px; / set the gap between columns /
-webkit-column-count: 3;
-webkit-column-gap: 10px;
column-count: 3;
column-gap: 10px;
width: 100%; / width of main container /
height: auto; / how high should the div element be? /
}


#masonry img {
display: inline-block; / img will be treated like a div, with respect to margin and padding. it allows elements to sit on either side of it /
width: 100%; / the img will take up 100% of the column */
}

There are several downfalls of using CSS3/HTML5 to create a masonry layout. Here are a few: 

  • Extra code is needed for proper responsiveness. Otherwise, it won't display correctly.
  • Some older browsers won't recognize it. 
  • It may not load as smoothly or quickly. 

I adore masonry layouts for photo galleries, and it looks wonderful with a bit of style added for effect. When you tinker with column-count and column-gap, you're able to control the rows of images visitors see. I recommend setting the main container to full, fluid width and setting your element height to auto. If you're looking to design a page with captions or headings, then replace img with whatever div element you'd like.The effects seen with jquery could be mimicked with animation and transition made available through CSS3. I'll leave that up to you for tinkering.The code relies on column-count, though, which is only supported in modern browsers. In older browsers, the masonry layout will appear broken, like it would without column-count. You could either code a fallback into your project, or check out Masonry by Desandro.


Leave your questions and comments below!

Tags — code-sharing css html
Categories — Code
Leave Comment