Suppose there are several div 's on the page. With or without class. And there are several div with the class .class-name , whose position in the document is unknown. But you need to choose the first (or second, third, fourth ...) div with the class. Class .class-name from the total.

Can I do this with CSS?

I thought it would work with. .class-name:nth-of-type(n) . But in this case, you have to manually specify the position of the total number of all div 's. And I would like to indicate it based on the number of divs with the class. class-name .

    3 answers 3

    As an option

     div { width: 50px; height: 50px; margin-bottom: 5px; background: aqua; } /* для 1 блока */ .class-name{ background: blanchedalmond; } .class-name ~ .class-name{ background: aqua; } /* для 2 блока .class-name ~ .class-name { background: blanchedalmond; } .class-name ~ .class-name ~ .class-name{ background: aqua; } */ /* для 3 блока и т.д .class-name ~ .class-name ~ .class-name{ background: blanchedalmond; } .class-name ~ .class-name ~ .class-name ~ .class-name{ background: aqua; } */ 
     <div>div</div> <div>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> <div>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> <div>div</div> <div>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> <div>div</div> <div>div</div> <div class='class-name'>div</div> <div>div</div> 

    • This implies a neighborhood div and will work only in this case. - Vadim Ovchinnikov 2:57
    • Thanks, but it works only for the first div'a. - A. Gusev
    • @A. Gusev in which case it will not work? - soledar10
    • @ soledar10 Sorry, question added. - A. Gusev
    • to select 2 (3 and higher) on the account of the block with the corresponding. class, the condition of choice is changed, but it can also be selected - soledar10

    You are thinking in the right direction. Just aside from the pseudo-class, the nth-of-type is also the first-of-typee and last-of-type, which select the first and the last element, respectively. For your case, the .class-name: first-of-type {} rule applies

    Unfortunately, this is not possible with CSS. nth-of-type , nth-child , etc. do not filter on a class and work being guided only by the ordinal number of an element concerning the parent regardless of classes.

    Only using jQuery is it possible to use the selector :eq .

    Another option is to add a class or CSS property using Javascript.

    • What is the ordinal number of the parent element? Who is the parent in this case? - Grundy
    • one
      corrected the formulation, thanks. I mean the sequence number of the element relative to the parent. - Vadim Ovchinnikov
    • It's a pity. I hoped that all the same there is a way. - A. Gusev