csscss-gridcss-counter

Automatic Numbering not incrementing


I want to recreate this picture using CSS, And I'm required to write the text using only CSS. I'm not allowed to edit the HTML code the required output

*{
    box-sizing: border-box;
    list-style:none;
    
}
.grid {
    background-color: #ddd;
    padding: 20px;
    width: 800px;
    height: 400px;
    margin: 20px auto;
    display: grid;
    grid-template-columns: auto auto auto;
    grid-template-rows: auto 1fr;
    gap: 10px;
    
   

  }
  .grid div{
    padding: 20px;
    background-color: darkgreen;
    display: flex;
    justify-content: center;
    align-items: center;
    list-style-type: none;
  
    
  }
  .grid div::before{
    counter-reset: Element 0;
    counter-increment: Element 1;
    content: "Element " counter(Element);
    color: white;
    justify-content: center;
    display: flex;
    align-items: center;
  }
<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="master.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS</title>
</head>

<body>
    <div class="grid">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>

</body>

</html>

It keeps showing only "Element 1" I used simple CSS code by resetting the counter and then making an increment of 1. And showing the output in content:counter(Element) this is my output


Solution

  • You need to set counter-reset to parent .grid, also no need to set 0

    Note you can improve your grid-template-columns: auto auto auto, to grid-template-columns: repeat(3, auto)

    * {
      box-sizing: border-box;
      list-style: none;
    }
    
    .grid {
      background-color: #ddd;
      padding: 20px;
      width: 800px;
      height: 400px;
      margin: 20px auto;
      display: grid;
      grid-template-columns: repeat(3, auto);
      grid-template-rows: auto 1fr;
      gap: 10px;
      counter-reset: Element;
    }
    
    .grid div {
      padding: 20px;
      background-color: darkgreen;
      display: flex;
      justify-content: center;
      align-items: center;
      list-style-type: none;
    }
    
    .grid div::before {
      counter-increment: Element;
      content: "Element " counter(Element);
      color: white;
      justify-content: center;
      display: flex;
      align-items: center;
    }
    <div class="grid">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>