Search code examples
htmltwitter-bootstrapmasonrycustom-font

Masonry and Bootstrap not rendering properly when custom font used (on a fresh load)


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?


Solution

  • 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