Layout
优质
小牛编辑
136浏览
2023-12-01
Item sizing
All sizing and styling of items is handled by your own CSS.
<div class="grid">
<div class="grid-item"></div>
<div class="grid-item grid-item--width2"></div>
<div class="grid-item grid-item--height2"></div>
...
</div>
.grid-item {
float: left;
width: 80px;
height: 60px;
border: 2px solid hsla(0, 0%, 0%, 0.5);
}
.grid-item--width2 { width: 160px; }
.grid-item--height2 { height: 140px; }
Responsive layouts
Item sizes can be set with percentages for responsive layouts. With the masonry
layout mode, set percentage-width columnWidth
with element sizing. Set percentPosition: true
so item positions are likewise set with percentages to reduce adjustment transitions on window resize.
<div class="grid">
<!-- width of .grid-sizer used for columnWidth -->
<div class="grid-sizer"></div>
<div class="grid-item"></div>
<div class="grid-item grid-item--width2"></div>
...
</div>
/* fluid 5 columns */
.grid-sizer,
.grid-item { width: 20%; }
/* 2 columns */
.grid-item--width2 { width: 40%; }
$('.grid').masonry({
// set itemSelector so .grid-sizer is not used in layout
itemSelector: '.grid-item',
// use element for option
columnWidth: '.grid-sizer',
percentPosition: true
})
imagesLoaded
Unloaded images can throw off Masonry layouts and cause item elements to overlap. imagesLoaded resolves this issue. imagesLoaded is a separate script you can download at imagesloaded.desandro.com.
Initialize Masonry, then trigger layout
after each image loads.
// init Masonry
var $grid = $('.grid').masonry({
// options...
});
// layout Masonry after each image loads
$grid.imagesLoaded().progress( function() {
$grid.masonry('layout');
});
Or, initialize Masonry after all images have been loaded.
var $grid = $('.grid').imagesLoaded( function() {
// init Masonry after all images have loaded
$grid.masonry({
// options...
});
});