When designing a site for a mobile interface, some designers prefer to use the fluid layout concept. This means that instead of assigning a fixed width to the columns, the width is set to a percentage of the size of the Masonry container. Assigning padding and margins correctly to the Masonry elements is similar to using fixed widths.
In the code bundle for this book, open the 3-fluid-layout.html
file in your preferred text editor to follow along.
Set the width of the Masonry elements to a particular percentage, and be sure to include the percentages of the padding and margins as well. For instance, if you want a four-column fluid layout, set the
width
property to20%
, setpadding
(both left and right padding) to1%
, andmargin
(both left and right margins) to1%
, making the total width of the Masonry item 24 percent.<style> .masonry-item { background: #FFA500; float: left; margin: 5px 1%; padding: 5px 1%; width: 20%; } </style>
The HTML structure (shown in the following code snippet) is pretty standard, as in the previous recipes:
<div id='masonry-container'> <div class='masonry-item '> Maecenas faucibus mollis interdum. </div> <div class='masonry-item '> Maecenas faucibus mollis interdum. Donec sed odio dui. </div> <div class='masonry-item '> Nullam quis risus eget urna mollis ornare vel eu leo. </div>
To achieve a fluid layout, we will pass in a function for
columnWidth
. It is important to match this up with the width you set for the Masonry items. Setting the width to 24 percent suggests a four-column layout.<script> $(function() { $('#masonry-container').masonry({ itemSelector: '.masonry-item', columnWidth : function(containerWidth) { return containerWidth / 4; } }); }); </script>
In our CSS styles, we defined the width of the Masonry elements to be 24 percent of the container width [20% width + (x2) 1% margin + (x2) 1% padding]. In the highlighted part of the previous code snippet, we can see that we passed a function to change the width of the column to 25 percent (because the container width is considered to be 100 percent, and we divided it by four).
Multi-columns can be implemented in a fluid layout as long as they are a factor of the fluid container width. For instance, if we have a four-column container, we can set the width of a two-column class to 46 percent with 1 percent each for margins and padding—a total width of 49 percent. Once we decide whether or not to go with a fluid layout, we need to be consistent when using percent versus pixels so as not to mix them up.