Search code examples
htmlcsscss-grid

CSS grid: appearance of no grid-row-gap depending on content of adjacent cells


main {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-column-gap: 60px;
        grid-row-gap: 60px;
    }
    
    p {
       grid-column: 2 / span 1;
       margin-bottom: 0;
       background-color: yellow;
    }
    
    p + p {
      margin-top: -60px;
     }
<main>
    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>
    <p>Another paragraph of text</p>
    <p>Possibly another paragraph of text</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>
</main>

I have a simple two column grid, with headings in the left column and paragraph text in the right hand column. I also have grid-row-gap set to give a nice gap between the rows. This all works fine, until after a heading, there is more than one paragraph <p> element. This second <p> element goes into a new row. I want all the <p> paragraph text to be inside one cell. Or for there to be no grid-row-gap between rows containing adjacent <p> elements. Or some sort of fudge.

This is what I want. Two columns. <h3> in left column. Text in right column. And if there is more than one <p> for there to be no grid-row-gap (or the appearance of no gap) between them.

<h3> | <p>
==========
<h3> | <p>
==========
<h3> | <p>
     | <p>
     | <p>
=========
<h3> | <p>

Here is my code

<main>
    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>
    <p>Another paragraph of text</p>
    <p>Possibly another paragraph of text</p>

    <h3>Heading</h3>
    <p>Some text, blah, blah blah</p>
</main> 

main {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-column-gap: 60px;
    grid-row-gap: 60px;
}

p {
   grid-column: 2 / span 1;
   margin-bottom: 0;
  background-colour: yellow;
} 

Solution

  • I would do the reasoning on the first child like below

    main {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-column-gap: 60px;
    }
    h3 {
      margin: 0;
    }
    p {
      grid-column: 2;
      margin: 0;
      background-color: yellow;
    }
    h3:not(:first-child),
    h3:not(:first-child) + p{
      margin-top: 60px
    }
    <main>
      <h3>Heading</h3>
      <p>Some text, blah, blah blah</p>
    
      <h3>Heading</h3>
      <p>Some text, blah, blah blah</p>
    
      <h3>Heading</h3>
      <p>Some text, blah, blah blah</p>
      <p>Another paragraph of text</p>
      <p>Possibly another paragraph of text</p>
    
      <h3>Heading</h3>
      <p>Some text, blah, blah blah</p>
    </main>