How to bold even p element with offset after h element in CSS?

I have a code like this:

<style> h2 ~ p:nth-of-type(2n+3) { font-weight: 600; } </style> <div> <h2>Cats</h2> <p>Normal cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <h2>Dogs</h2> <p>Normal dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> </div> 

I cannot change HTML or use jQuery or JS. I need to use CSS to make weird dogs and cats bolder. But when I show above the code, not only weird cats and dogs are bolder, but also the first normal dog:

Example

CSS cats seem to be expanding their use for dogs.

How to set a CSS selector to make only weird cats and dogs bolder?

+1
source share
2 answers

You can override the Normal dog style using h2 + p:nth-of-type(2n+3) . Check below.

 h2 ~ p:nth-of-type(2n+3) { font-weight: 600; } h2 + p:nth-of-type(2n+3) { font-weight: normal; } 
 <div> <h2>Cats</h2> <p>Normal cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <h2>Dogs</h2> <p>Normal dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> </div> 
0
source

As stated here , you can do this using the css ~ selector and then the nth-of-type selector (alternatively nth-child ).

However, this will also select every seventh element, so you will have to override this with the :not selector. You can learn more about these selectors in MDN: Generic selector and : nth-of-type and : not .

You can use the following, which is a bit flexible:

 h2 ~ p:nth-of-type(2n+3):not(:nth-of-type(6n+1)){ font-weight: 600; } 

Although you note that the markup is static, the above selector will work if you add more β€œlists” of animals. Obviously, the order of the animals weird and normal cannot change. A strange animal should be third and fifth in order.

For instance:

 h2 ~ p:nth-of-type(2n+3):not(:nth-of-type(6n+1)) { font-weight: 600; } 
 <div> <h2>Cats</h2> <p>Normal cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <p>Weird cat</p> <p>Normal cat</p> <h2>Dogs</h2> <p>Normal dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> <p>Weird dog</p> <p>Normal dog</p> <h2>Birds</h2> <p>Normal bird</p> <p>Normal bird</p> <p>Weird bird</p> <p>Normal bird</p> <p>Weird bird</p> <p>Normal bird</p> <h2>Monkeys</h2> <p>Normal monkey</p> <p>Normal monkey</p> <p>Weird monkey</p> <p>Normal monkey</p> <p>Weird monkey</p> <p>Normal monkey</p> </div> 
0
source

All Articles