Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS same class after n-th level

CSS:

.discussionLevel-1 {padding: 20px 0px 20px 70px;}
.discussionLevel-2 {padding: 20px 0 20px 90px;}
.discussionLevel-3 {padding: 20px 0 20px 110px;}

I am trying to set every n>3 to n=3.

Q: How to use selectors for

.discussionLevel-4
.discussionLevel-5
.discussionLevel-6
...

etc to be same as .discussionLevel-3 ?

Any ideas?

like image 427
Ing. Michal Hudak Avatar asked Aug 12 '26 02:08

Ing. Michal Hudak


2 Answers

You need :nth-child(n+3) selector for this. Assuming you have a wrapper div.

Working Demo

HTML

<div class="discussion">
<div class="discussionLevel-1">hi</div>
<div class="discussionLevel-2">hi</div>
<div class="discussionLevel-3">hi</div>
<div class="discussionLevel-4">hi</div>
<div class="discussionLevel-5">hi</div>
<div class="discussionLevel-6">hi</div>
<div class="discussionLevel-7">hi</div>
</div>

CSS

.discussionLevel-1 {padding: 20px 0px 20px 70px;}
.discussionLevel-2 {padding: 20px 0 20px 90px;}

.discussion div:nth-child(n+3) {padding: 20px 0 20px 110px;} 
/*All div after and including div 3*/
like image 67
Surjith S M Avatar answered Aug 16 '26 03:08

Surjith S M


You can use nth-child there, won't respect your classes though it will do the same job for you... If you are dealing with various elements on the same level than prefer using nth-of-type instead of nth-child

Demo

You haven't provided the DOM so am going with ul and li here

ul li:nth-child(1n) {
    color: red;
}

ul li:nth-child(2n) { /* Targets every 2nd element */
    color: green;
}

ul li:nth-child(3n) { /* Targets every 3rd element */
    color: blue;
}

Still not sure when I read this etc to be same as .discussionLevel-3 so if you want to target all the elements followed .discussionLevel-3 on the same level to be applied the styles than you can use ~

.discussionLevel-3,
.discussionLevel-3 ~ div[class^="discussionLevel-"] {
   /* Styles */
}
like image 33
Mr. Alien Avatar answered Aug 16 '26 03:08

Mr. Alien