The craft of masonry is known for its creation of intentional gaps

I've gone through all the posts related to this issue, but none of the suggested solutions seem to work for me.

Here is a visual representation of my grid:

https://i.sstatic.net/ybufk.png

If you want to see the code and play around with it, check out this jsfiddle. Below is the HTML snippet provided:

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Masonry -->
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<link rel="stylesheet" href="css/style.css">


<!-- imagesLoaded -->
<script 
src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae3e7ebedeff9e6e5ebeeefeecabea4bb">[email protected]</a>/imagesloaded.pkgd.min.js">

// Initialize Masonry
var $grid = $('.grid').masonry({
  itemSelector: '.grid-item',
  percentPosition: true,
  columnWidth: '.grid-sizer'
});
// Rearrange layout after each image loads
$grid.imagesLoaded().progress( function() {
  $grid.masonry('layout');
});
</script>


<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


<body>

  <div class="container">

        <div class="grid">

          <div class="grid-item">
              <img src="http://hiphopgoldenage.com/wp-content/uploads/2015/10/MellowManAce.jpg" alt="Mellow Man Ace">
          </div>

          <div class="grid-item">
              <img src="https://pbs.twimg.com/media/C2O6p6ZWgAA67jA.jpg" alt="...">
          </div>

          <div class="grid-item">
              <img src="http://images1.mtv.com/uri/mgid:file:docroot:mtv.com:/shared/promoimages/bands/c/cypres_hill/photos/cr_rene_cervantes/flipbook/CH-0141.jpg?enlarge=false&matte=true&matteColor=black&quality=0.85" alt="...">
          </div>

          <div class="grid-item">
              <img src="https://cdn-images-1.medium.com/max/600/1*VfCrfkNhTVwAxftgfebcog.jpeg" alt="...">
          </div>

          <div class="grid-item">
              <img src="https://images.genius.com/ace91b03cd16b6f3678660cd184af26a.500x323x1.jpg" alt="...">
          </div>

          <div class="grid-item">
              <img src="https://images.pexels.com/photos/271560/pexels-photo-271560.jpeg" alt="...">
          </div>

          <div class="grid-item">
              <img src="https://images.pexels.com/photos/147504/pexels-photo-147504.jpeg" alt="...">
          </div>

          <div class="grid-item">
              <img src="https://images.pexels.com/photos/99551/hot-air-balloon-valley-sky-99551.jpeg" alt="...">
          </div>

        </div>

CSS:

* { box-sizing: border-box; }

/* Ensure scrollbar visibility */
html { overflow-y: scroll; }
/* body { font-family: sans-serif; } */

/* ---- Grid Style ---- */
.grid {
  background: #DDD;
}

/* Clearfix */
.grid:after {
  content: '';
  display: block;
  clear: both;
}

/* ----Individual Grid Item Styling---- */
.grid-sizer,
.grid-item {
  width: 33.333%;
  float: left;
}
.grid-item img {
  display: block;
  max-width: 100%;
}

What am I missing here? Your guidance would be greatly appreciated. Thank you!

Answer №1

To properly implement the JavaScript code, ensure that you enclose it within its own script tag (without a src). Additionally, make sure to include the jQuery code used with imagesLoaded() inside $(document).ready() or $(function(){}). Avoid specifying the columnWidth in your layout as the column width is already defined in your CSS.

.grid {
  background: #DDD;
}

.grid:after {
  content: '';
  display: block;
  clear: both;
}

.grid-sizer,
.grid-item {
  width: 33.333%;
  float: left;
}

.grid-item img {
  display: block;
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e78e8a868082948b8886838283a7d3c9d6">[email protected]</a>/imagesloaded.pkgd.min.js"></script>
<script>
  $(function() {
    var $grid = $('.grid').masonry({
      itemSelector: '.grid-item',
      percentPosition: true,
    });
    $grid.imagesLoaded().progress(function() {
      $grid.masonry('layout');
    });
  });
</script>

<div class="grid">
  <div class="grid-item">
    <img src="http://hiphopgoldenage.com/wp-content/uploads/2015/10/MellowManAce.jpg" alt="Mellow Man Ace">
  </div>
  <div class="grid-item">
    <img src="https://pbs.twimg.com/media/C2O6p6ZWgAA67jA.jpg" alt="...">
  </div>
  <div class="grid-item">
    <img src="http://images1.mtv.com/uri/mgid:file:docroot:mtv.com:/shared/promoimages/bands/c/cypres_hill/photos/cr_rene_cervantes/flipbook/CH-0141.jpg?enlarge=false&matte=true&matteColor=black&quality=0.85" alt="...">
  </div>
  <div class="grid-item">
    <img src="https://cdn-images-1.medium.com/max/600/1*VfCrfkNhTVwAxftgfebcog.jpeg" alt="...">
  </div>
  <div class="grid-item">
    <img src="https://images.genius.com/ace91b03cd16b6f3678660cd184af26a.500x323x1.jpg" alt="...">
  </div>
  <div class="grid-item">
    <img src="https://images.pexels.com/photos/271560/pexels-photo-271560.jpeg" alt="...">
  </div>
  <div class="grid-item">
    <img src="https://images.pexels.com/photos/147504/pexels-photo-147504.jpeg" alt="...">
  </div>
  <div class="grid-item">
    <img src="https://images.pexels.com/photos/99551/hot-air-balloon-valley-sky-99551.jpeg" alt="...">
  </div>
</div>

Answer №2

If you're working with percentages for your grid items and want to calculate the column width automatically, it's best to use a real width value.

Here's one way to achieve this:

$('.grid').masonry({
  // options
  itemSelector: '.grid-item',
  columnWidth: $(".grid-item").width()
});

For a demonstration, check out this example: https://jsfiddle.net/hqLj5t55/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to implement dependency injection within a .css document?

I have a C# .NET 6 application. Some of the web pages (Razor Pages) in the app use dependency injection to inject configuration into the Razor Pages (.cshtml files), allowing certain config elements to be displayed in the user interface. My query is, can ...

"Enhance your website with a creative CSS3 effect: rotating backgrounds on

Greetings, fellow coders! #div1{ position: fixed; top: 50%; left: 50%; margin-left:-100px; margin-top: 420px; width: 158px; height: 158px; background-image:url(imag ...

What is the best way to prevent table cell borders from encroaching on the padding area of the cell?

When dealing with table cell elements that have borders, it's common for them to not respect the vertical height of the cell containing them. Sometimes a child element's borders may overlap the padding or border of its containing cell. To prevent ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

The accumulation of classes occurs during the cloning process of a template used for a data array

Encountered an issue while duplicating a template div to generate elements for a dataset. The problem arises from classes stacking up when creating elements for each data entry. Sample JavaScript code: $(document).ready(function(){ var data = [ { ...

Is NextJS Route Handler in Version 13 Really Secure?

Within my forthcoming NextJS 13 web application, I am in the process of integrating an API through route handlers to facilitate functions like user registration and login procedures. Is it considered safe when transmitting sensitive data like a user's ...

Sending JSON data from AngularJS to Laravel Controller through POST request

I have encountered an issue while using AngularJS to send POST data to a Laravel controller for saving into a database. The problem lies in the incorrect parsing of data from AngularJS to Laravel. The data being passed looks like this: $scope.invoice_ite ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

The functionalities of $scope and this in AngularJS

Currently, I am developing a small application using angularjs. In this project, I am trying to implement a feature that involves deleting a contact. The functionality itself works perfectly fine, however, I am encountering an issue where the 'this.op ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...

Rotational orientation of a progress circle image in SVG

I am currently working on developing a circular progress bar, similar to the one shown in the image below. The progress of this bar is determined by percentages and it moves around the circle accordingly. I have managed to get the progression moving, b ...

Is it feasible for nested div to remain unaffected by bleeding when the container is positioned relatively and has an overflow hidden

Is it possible to bleed a nested div even when the container is positioned relative with hidden overflow? In this case, giving the nested div a fixed position is not an option. Please check out this unique example: http://jsfiddle.net/s7nhw/11/. If you ...

Certain components display with greater height on Internet Explorer

When viewing my website in Internet Explorer, I noticed that some elements appear taller compared to other browsers. After investigating further, I discovered that all these elements contained SVG images. It seems like they have a fixed height even though ...

Is there a way to arrange the components of my form so that the questions are positioned on the left side and the choices are displayed on the right

As I am creating a form, my goal is to align the information within it in a way that places the questions on the left side and the options on the right. I have experimented with utilizing IDs, centering them, and adjusting their positioning from left to r ...

In the year 2018, a special named anchor was created that, when clicked, conceals all

Hello, I'm facing a frustrating issue with my webpage that is driving me crazy. I have a simple hyperlink <a href="#OrientationSchedule">See schedule below</a>. When clicked, it navigates to the named anchor further down on the same page, ...

Displaying retrieved data following AJAX request in ASP.NET MVC is currently not functioning

I have a situation where I need to populate two <p> fields with text Below is the HTML code snippet: <p id="appId" style="visibility: hidden;"></p> <p id="calculationId" style="visibility: hidden;"></p> I am making an AJAX ...

Rotating images with React

I am encountering an issue with implementing an image carousel in React. Previously, it worked perfectly when I was not using React, but now that I am migrating the page, I am facing an error. ** The carousel is located on the home page: ** const Home = ( ...