Search code examples
htmlcsscss-grid

Positioning list elements using grid in CSS


I am trying to implement a grid in css which contains two rows, first row has 3 columns which each columns contain one of the li elements, and the second row contains the fourth li element from the unordered list. I am required to not modify the html code. Ps. this is for learning purpose so any help is greatly appreciated.

.unordered_list {
  display: grid;
}
<ul class="unordered_list">
  <li>
      <img src="logo.png" alt="car">
      <p>It should be column of 3</p>
  </li>
  <li>
      <img src="logo.png" alt="car">
      <p>It should be column of 3</p>
  </li>
  <li>
      <img src="logo.png" alt="car">
      <p>It should be column of 3</p>
  </li>
  <li>
      <h2>Head H2 Text</h2>
      <p>Should be a row</p>
  </li>
</ul>


Solution

  • You need to draw your columns and rows using grid-template-columns and grid-template-rows on the container element.

    then specify the start and end of each grid item using grid-column: <start-line> / <end-line> and grid-row: <start-line> / <end-line>

    Click here for a strong well illustrated guide to use Grid

    and preview the snippet I included for a solution for your needed grid.


    **Snippet is edited to more simple solution

    .unordered_list {
      display: grid;
      width: 300px;
      height: 200px;
      grid-template-columns: repeat(3, 100px [col-start]);
      grid-template-rows: 50% 50%;
      list-style: none;
    }
    
    li {
      text-align: center;
      padding: 10px;
      border: 1px solid #eee;
    }
    
    .unordered_list li:last-child {
      grid-column: 1 / 4;
    }
    <ul class="unordered_list">
      <li>
        <img src="logo.png" alt="car">
        <p>It should be column of 3</p>
      </li>
      <li>
        <img src="logo.png" alt="car">
        <p>It should be column of 3</p>
      </li>
      <li>
        <img src="logo.png" alt="car">
        <p>It should be column of 3</p>
      </li>
      <li>
        <h2>Head H2 Text</h2>
        <p>Should be a row</p>
      </li>
    </ul>