Search code examples
htmlcsscss-grid

css grid a 2² grid with two titles and two lists


I want to have a 2x2 grid with two h3 on top and two ul in the bottom

#listgallery {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-areas: "title" "list";
}

h3 {
  grid-area: title;
}

ul {
  grid-area: list;
}
<div id="listgallery">
<h3>title1</h3>
<ul>
  <li>list1</li>
</ul>
<h3>title2</h3>
<ul>
  <li>list2</li>
</ul>
</div>

that displays all header over eachother same as lists

#listgallery {
            display: grid;
            grid-template-columns: 1fr 1fr;
            grid-template-areas:
            "title title"
            "list list"
            ;
            h3 {
                grid-area:title;
            }
            ul {
                grid-area:list;
            }
        }

same as above

#listgallery {
            display: grid;
            grid-template-columns: 1fr 1fr;
        }

this displays headers on the left lists on the right I could use that and adjust my html like this:

<h3>title</h3>
<h3>title</h3>
<ul><li>list</li></ul>
<ul><li>list</li></ul>

but that feels just wrong. So is there any css solution to solve that?


#listgallery {
 display: grid;
 grid-template-columns: 1fr 1fr;
}
#listgallery h3 {
 grid-row: 1;
}
#listgallery h3:nth-child(7), #listgallery h3:nth-child(5) {
 grid-row: 3;
}
<div id="listgallery">
<h3>title1</h3>
<ul>
  <li>list1</li>
</ul>
<h3>title2</h3>
<ul>
  <li>list2</li>
</ul>
<h3>title3</h3>
<ul>
  <li>list3</li>
</ul>
<h3>title4</h3>
<ul>
  <li>list4</li>
</ul>
</div>

that works for some reason but the css still isn't pretty


Solution

  • For that little of elements, you can make your code simplier and may use only what is needed .

    #listgallery {
      display: grid;
      grid-template-columns: 1fr 1fr; 
    }
    
    h3 {
      grid-row: 1;
    }
     
    <div id="listgallery">
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      </div>


    to be clarified from comment:

    #listgallery {
      display: grid;
      grid-template-columns: 1fr 1fr; 
    }
    
    h3 {
      grid-row: 1;
    }
    h3 ~h3 ~h3 {
    grid-row: 3
    }
    <div id="listgallery">
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      <h3>title</h3>
      <ul>
        <li>list</li>
      </ul>
      </div>