Css nth-child with another element lookup method

Is there a way, for example, to specify css code for the 5th .slide element as follows:

HTML

<div id="slides"> <section> <div class='slide'></div> this should be 1 <div class='slide'></div> this should be 2 <div class='slide'></div> this should be 3 </section> <section> <div class='slide'></div> this should be 4 </section> <section> <div class='slide'></div> this should be 5 I target this one <div class='slide'></div> this should be 6 <div class='slide'></div> this should be 7 </section> </div> 

CSS

 .slide:nth-of-type(5) { background:red; } 

I thought something like this would work, but it is not.

I basically want to get each item with the corresponding number, so the 7th with a seven in css

I am open to jquery solutions if necessary

+4
source share
4 answers

JQuery Solution

 $('#slides .slide').eq(4).css("color", "red"); 

 $('#slides .slide').eq(4).css("color", "red"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="slides"> <section> <div class='slide'>this should be 1</div> <div class='slide'>this should be 2</div> <div class='slide'>this should be 3</div> </section> <section> <div class='slide'>this should be 4</div> </section> <section> <div class='slide'>this should be 5 I target this one</div> <div class='slide'>this should be 6</div> <div class='slide'>this should be 7</div> </section> </div> 
+1
source

It will not work this way, it will only target .slide in this section:

 section:nth-of-type(3) .slide:first-of-type { background:red; } 
 <div id="slides"> <section> <div class='slide'></div> this should be 1 <div class='slide'></div> this should be 2 <div class='slide'></div> this should be 3 </section> <section> <div class='slide'></div> this should be 4 </section> <section> <div class='slide'>this should be 5 I target this one </div> <div class='slide'>this should be 6</div> <div class='slide'>this should be 7</div> </section> </div> 
+1
source

Here ya go http://jsfiddle.net/DIRTY_SMITH/ns3u7uf5/12/

CSS

 section:nth-child(3) > .slide:nth-child(1) { color:red; } 

HTML

 <div id="slides"> <section> <div class='slide'> this should be 1</div> <div class='slide'> this should be 2</div> <div class='slide'> this should be 3</div> </section> <section> <div class='slide'> this should be 4</div> </section> <section> <div class='slide'> this should be 5 I target this one</div> <div class='slide'> this should be 6</div> <div class='slide'> this should be 7</div> </section> </div> 
0
source

You are trying to use a selector designed for types in a class. Hence the name is nth-of-type . Unfortunately, as far as I know, there is no way to use this selector for classes.

You can use program logic to add new classes for each interval that you want. Then you can use something like this:

 section.highlight { color:red; } 

Someone faced the same situation: css3 nth type, restricted by class

-one
source

All Articles