Choose the nth next brother

I wondered if there is a better solution than what I found without changing the html structure

The HTML structure looks like this:

<div class="wrap"> <div class="divider"></div> <div class="block"></div> <div class="block"></div> <div class="divider"></div> </div> 

So the different DIVs on the same level, what I want to do is color every fourth block differently until a separator appears, then it will have to recount.

I thought something like .block:nth-child(4n) would do the trick, but in fact it takes into account elements based on the parent, and not based on the class.

Here's a JSFiddle to try. Lock No. 4 and No. 8 in each line should be different http://jsfiddle.net/SKgdH/3/

And here is how I did this work: http://jsfiddle.net/SKgdH/1/

What I did was find the fourth brother of this delicator .divider + .block + .block + .block + .block

This works, however, I have to write the same for block 8, 12, 16, .., which no longer makes it automatic.

Is there something like .divider + .block:nth-sibling(4) or .divider + .block:nth-of-class(4) ?

Perhaps you have an idea on how to solve this problem without changing the source code or using javascript.

+8
css css-selectors
source share
3 answers

Such a pseudo-class will not work because you expect it to correspond to elements relative to another component selector, which is not how simple selectors work. For example, if you wrote a complex selector in which there was only one compound selector with this pseudo-class (and there are no combo counters):

 .block:nth-sibling(4n) 

Do you expect this to match .block:nth-child(4n) , nothing matches or is invalid?

It would be nice to have abridge + .block + .block + .block + .block and make it somehow repeat, but, unfortunately, due to the way the selector syntax is designed, this is simply impossible.

You will need to use JavaScript and / or add additional classes to the corresponding elements.

+11
source share

The problem here is that :nth-of-type refers to the type of the element , and both .divider and .block are elements of type <div> .

What you really need for a .divider to be another element type from .block .


In this case, if only two children are <div class="wrap"> :

  • <div class="divider">
  • <div class="block">

I would like to replace <div class="divider"> with <hr> - the theme gap element.

Then you can use:

  .wrap div:nth-of-type(4) 

in the style of .block .

+1
source share

As explained by BoltClock, you cannot do this without JavaScript. If you choose this route (although you explicitly say no JavaScript), this can be done using jQuery as follows:

 var counter = 0; $('.wrap > div').each(function() { if ($(this).hasClass('divider')) { counter = 0; } else if ($(this).hasClass('block')) { counter++; if (counter % 8 == 4) { $(this).css('background-color','#ff0'); } } }); 

This will be the color of the 4th column in each row of yellow.

0
source share

All Articles