someone
someone

Reputation: 691

how to style list with nth-child()

I have the following code.

html

    export default function App() {
      const data = [
        { id: 1, title: "1" },
        { id: 2, title: "2" },
        { id: 3, title: "3" },
        { id: 4, title: "4" },
        { id: 5, title: "5" },
        { id: 6, title: "6" },
        { id: 7, title: "7" },
        { id: 8, title: "8" },
        { id: 9, title: "9" },
        { id: 10, title: "10" },
        { id: 11, title: "11" }
      ];
      return (
        <div className="App">
          {data.map((el) => (
            <div key={el.id} className="block">
              {el.title}
            </div>
          ))}
        </div>
      );
    }

css

    .App {
      display: grid;
      grid-template-columns: 50% 50%;
    }

    .block {
      border: 1px solid black;
      height: 50px;
    }

    .block:nth-child(3n + 1) {
      background-color: red;
    }

    .block:nth-child(3n + 2) {
      background-color: green;
    }

    .block:nth-child(3n + 3) {
      background-color: blue;
    }

I am trying to give my .block class the following styles. But it's not working. I tried (3n + 1) for red (3n + 2) for green and (3n + 3) for blue. Also, I tried to do something with :first-child() for red but also it's not worked

Please help me to achieve the expected result as in the picture. thanks

enter image description here

Upvotes: 3

Views: 30

Answers (1)

Tom
Tom

Reputation: 5677

You can think in groups of 4 :

  • The first and the last elements are red (4n+1 and 4n).

  • The second element is green (4n+2).

  • The third element is blue (4n+3).

.App {
  display: grid;
  grid-template-columns: 50% 50%;
}

.block {
  border: 1px solid black;
  height: 50px;
}

.block:nth-child(4n),
.block:nth-child(4n+1) {
  background-color: red;
}

.block:nth-child(4n+2) {
  background-color: green;
}

.block:nth-child(4n+3) {
  background-color: blue;
}
<div class="App">
  <div class="block">1</div>
  <div class="block">2</div>
  <div class="block">3</div>
  <div class="block">4</div>
  <div class="block">5</div>
  <div class="block">6</div>
  <div class="block">7</div>
  <div class="block">8</div>
  <div class="block">9</div>
  <div class="block">10</div>
  <div class="block">11</div>
  <div class="block">12</div>
</div>

Upvotes: 2

Related Questions