问题
I have 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 can not change HTML or use jQuery or JS. I need to use CSS to make weird dogs and cats bolder. But when i display above code not only weird cats and dogs are bolder, but also first normal dog:
It seems like the CSS matching Cats extends its use to Dogs.
How to set the CSS selector to make only weird cats and dogs bolder?
回答1:
You can override the style for Normal dog 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>
回答2:
As stated here, you can do this by using the css ~
selector, followed by the nth-of-type
(alternatively nth-child
) selector.
However, this would also select every 7th item, so you have to override that by using the :not
selector too. You can read more about it these selectors on the MDN: General Sibling Selector and :nth-of-type and :not.
You could use the following, which is a bit flexible:
h2 ~ p:nth-of-type(2n+3):not(:nth-of-type(6n+1)){
font-weight: 600;
}
Even though you mention that the markup is static, the above selector will work should you add more "lists" of animals. Obviously, the order of weird
and normal
animals cannot change. The weird animal has to be the 3rd and 5th in the order.
For example:
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>
来源:https://stackoverflow.com/questions/37408891/how-to-bolder-even-p-element-with-offset-after-h-element-in-css