cssmultiple-columnstailwind-cssmasonry

Why does css columns separate HTML blocks?


I am trying to create a masonry grid like structure with images. More specfically, I am rendering a list of <figure> elements with <img> and <figcaption> children elements. However, when I display the data in the browser, the image and figcaption separate.

I am using Tailwind CSS for styling.

Why is this the case and how can I fix it?

I've tried using flexbox and grid, but they 1) weren't as precise as plain columns and 2) didn't achieve what I wanted anyways

Here is the codepen link


Solution

  • All you need is to use break-inside: avoid-column for the <figure> elements, so that the element will not be broken across multiple columns:

    figure {
      break-inside: avoid-column;
    }
    

    See proof-of-concept below, with markup copied from your CodePen:

    div {
      max-width: 1200px;
      margin: 0 auto;
      columns: 3;
      column-gap: 15px;
    }
    
    figure {
      break-inside: avoid-column;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet"/>
    <div class="">
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/6059CAD8-02E8-2E00-2922DF84800167E0.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/3C7AC799-1DD8-B71B-0B4E94DE10F014E5.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/3C7AC355-1DD8-B71B-0B9C2F07853F39F1.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/3C7AC4C1-1DD8-B71B-0B8592CA6634ABEE.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/3C7AC638-1DD8-B71B-0BD28B3407821A15.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    
      <figure class="mb-10 text-center">
        <img class="rounded-xl" src='https://www.nps.gov/common/uploads/structured_data/3C7AC8F5-1DD8-B71B-0B661B7FF90F5407.jpg' />
        <figcaption class="mt-4 text-sm italic text-gray-600 ">Caption here</figcaption>
      </figure>
    </div>