1

I'm trying to select all of the 'classes' class, except the first 3. I'm not sure why my syntax is incorrect. Can someone explain what I'm doing wrong here?

I've tried a few different combos, like including the class name in the selector before nth of type, and others.

.classes {
  background: red;
  width: 200px;
  height: 30px;
  margin-bottom: 5px;
}

.classes:not(.classes:nth-of-type(1)), .classes:not(nth-of-type(2)), .classes:not (nth-of-type(3)) {
  background: blue;
}

.classes:nth-of-type(6) {
  background: orange;
}
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
<div class='classes'>test</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
user8758206
  • 2,106
  • 4
  • 22
  • 45

1 Answers1

3

You can use this:

.classes {
    background: green;   
}
.classes:nth-child(n+4) {
    background: red;
}

You can find more useful :nth-child examples here

If you want to use exactly the :not selector, you can try this:

.classes:not(:first-child):not(:nth-child(2)):not(:nth-child(3)) {
  background: yellow;
}
James
  • 109
  • 12
  • this is not a generic way, and it won't work all the time ... depend on the structure – Temani Afif May 09 '18 at 09:04
  • It selects all of the classes, except the first 3, as stated in the question. – James May 09 '18 at 09:06
  • no, it's select ALL the elements starting from the fourth one that have .classes ... so this work in this case because all the element have the same class, but it's not generic ... by the way you can simply do `nth-child(n+4)` it will also do the same – Temani Afif May 09 '18 at 09:07
  • I like your solution! But say if i wanted to not select the first 3, but also if there were a list of 20 and I didnt want to select the 17th item, how could the :not selector achieve this? (instead of .classes:nth-last-child(4) ) – user8758206 May 09 '18 at 09:15
  • 1
    I believe the easier and less complex solution would be to add the 17th element to the first CSS selector, like this: `.classes, .classes:nth-child(17) { background: green; } .classes:nth-child(n+4) { background: red; }` . But if you are trying to apply this to grid elements, the solution might be different. Please let me see a screenshot of what you're working on and I will help. – James May 09 '18 at 09:21
  • @user8758206 the last one will not work because the second selector will be more specific and override the first one : https://jsfiddle.net/nn3mso3x/1/ – Temani Afif May 09 '18 at 09:24
  • I've edited the answer by providing a solution applicable for you. – James May 09 '18 at 09:31