1

I am following this Masonry & Bootstrap example.

And it works well until I am trying to use a custom Font. Then if the final boxes size is different with the custom Font that without it, the distribution of the boxes is not calculated properly.

Looks like Masonry code is executed before the font is loaded, it makes the calculations but then the font is loaded and the boxes sizes changes.

Here there is a working codepen example:

I am adding this:

<style>
  /* Importing the fonts */
  @import url('https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&display=swap');

  body {
    font-family: 'Libre Baskerville', serif;
  }
</style>

Try to reload without cache (cmd + shift + R (in Mac Chrome)).

Wrong distribution: enter image description here

Right distribution (second load): enter image description here

How is the proper way to handle this?

fguillen
  • 36,125
  • 23
  • 149
  • 210

2 Answers2

0

I'd guess a solution will be similar to what's suggested in this answer on Reload Masonry Grid after AJAX call would do. See also this answer on How to be notified once a web font has loaded.

You might even hide the grid with CSS until that's done (visibility or opacity), then show it.

document.fonts.ready.then(function () {
  grid.reloadItems();
  gridContainer.classList.add('nice-fade-effect-class');
});
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • It didn't work, tested in this codepen: https://codepen.io/fguillen/pen/zYLEpbm – fguillen Jan 17 '23 at 17:29
  • `reloadItems()` not working, but initializing the grid after the fonts are loaded yes: https://stackoverflow.com/a/75150196/316700 an issue has been added in github https://github.com/desandro/masonry/issues/1182 – fguillen Jan 17 '23 at 17:38
0

Based on a variant of the @isherwood's answer, the only thing that worked for me was to initialize the grid just after the fonts were loaded:

<div class="row grid" id="masonry-grid">
  <div class="col-sm-12 col-lg-4 mb-4 grid-item">[...]</div>
  <div class="col-sm-12 col-lg-4 mb-4 grid-item">[...]</div>
  <div class="col-sm-12 col-lg-4 mb-4 grid-item">[...]</div>
</div>

<script>
    document.fonts.ready.then(function () {
        console.log("Fonts ready");
        new Masonry('#masonry-grid', {
            itemSelector: '.grid-item'
        });
    });
</script>

Here is the working codepen: https://codepen.io/fguillen/pen/poZWaoL

fguillen
  • 36,125
  • 23
  • 149
  • 210