I'm creating a 2 column masonry layout using images of different sizes. The images can be any size as long as they have the greatest common divisor (as required by the Masonry plugin).
In order to make the layout responsive I'm converting the width of the masonry items into percent (or I can use min-width and width 100%).
Update: I noticed that many who answer make both columns 50% as a solution. That works but is not the goal. Images have to retain their original image size. They can shrink but keep the same ratio.
$(function () {
var container = $('#container');
// Convert .box width from pixels to percent
$('.box').find('img').each(function () {
var percent = ($(this).width()) / container.width() * 100 //convert to percent;
$(this).closest('.box').css('max-width', percent + '%');
});
// Trigger masonry
container.masonry({
itemSelector: '.box',
columnWidth: 1 //widths dividable by 1
});
});
jsfiffle: http://jsfiddle.net/AMLqg/278/
This seems to work. The items are fluid when you resize the window. However if you load the script in a small window size (smaller than the 2 column width) the items collapse. How can I keep the masonry items responsive on window load even when the window is smaller?
Update: Here is more info for a better understanding. I'm trying to keep 2 responsive columns regardless of the window size. The columns can't have equal widths because the images have different widths. For this reason I'm using columnWidth: 1
because all widths are dividable by 1.
Please see images below for examples.
Problem: When you open the page in a small window the elements are collapsed. When you resize the window to be larger the elements remain collapsed until the window width is larger than the width of both elements.
Goal: I'm trying to keep the elements in 2 responsive columns on load like in the image below. Currently they remain responsive if on load the window is large and you resize it to be smaller but not vice verse when window is small on load and you make it larger.
$(window).load(function() {
and try again. See if that works. Images do not havewidth
/height
, until they are loaded.$(document).ready
fires, before images are loaded. – Telegonusmin-width
CSS property to keep that from happening. Check out @JoshBurgess's answer. – Rainstorm$(function()
has the same functionality I believe. I tried on load too but doesn't work. – Baklava