如何在Masonry网格中居中图片?解决右侧留白问题
Hey there, I feel your pain—spending days on a layout issue is no fun. Let's get that Masonry grid centered properly and get rid of that annoying right-side white space.
The Root Cause
Right now, your Masonry container has margin: 0 auto, but Masonry's default behavior is to left-align items within the container. Without telling it to adjust the container width to fit the columns, the container will take up full available width, leaving empty space on the right when the total column width doesn't fill the container.
Step-by-Step Fix
Add
fitWidth: trueto your Masonry initialization
This is the key setting that tells Masonry to calculate the exact width needed for your columns and shrink the container to that width. Combined withmargin: 0 autoon the container, this will center the entire grid.Modified JS code:
var container = document.querySelector('#masonry'); var msnry = new Masonry(container, { columnWidth: 50, itemSelector: '.item', fitWidth: true // Enables container width adjustment for centering });Tweak your CSS for better spacing and container constraints
- Add a
max-widthto the#masonrycontainer to prevent it from stretching too wide on large screens. - Add small horizontal margins to
.itemto create spacing between columns (your current zero margins make items feel cramped anyway).
Updated CSS:
#masonry { margin: 0 auto; max-width: 1200px; /* Adjust this to your desired maximum grid width */ } .item { min-width: 10px; max-width: 600px; min-height: 50px; margin: 0 5px 10px; /* Horizontal margins for column spacing, vertical for row spacing */ border: 0; border-color: transparent; }- Add a
Optional: Ensure images load before initializing Masonry
If your images are loading after Masonry initializes, the layout might jump or not calculate correctly. Use theimagesLoadedlibrary (included with Masonry) to wait for images to load first:imagesLoaded(container, function() { var msnry = new Masonry(container, { columnWidth: 50, itemSelector: '.item', fitWidth: true }); });
Why This Works
fitWidth: truemakes the Masonry container only as wide as the total width of your columns, somargin: 0 autocan properly center it in the parent.- The added margins on
.itemcreate clean spacing between your images without breaking the Masonry layout. - Setting a
max-widthon the container ensures your grid doesn't become too wide on large displays, keeping your design consistent.
Give these changes a try—your grid should now be centered with no awkward right-side white space!
内容的提问来源于stack exchange,提问作者Navjot Singh

