I have a HTML that is messed and i can not change it, it looks like this:
<div>
<h2>This is a title cat</h2>
<p>This is a message</p>
<p>One cat</p>
<p>Two cat</p>
<p>Three cat</p>
<h2>This is a title dog</h2>
<p>Dog 0</p>
<p>Dog 1</p>
<p>Dog 2</p>
<p>Dog 3</p>
</div>
Now i would like to make every odd p that comes after a h2 element bolder. So i would like this to be in bold:
This is a message
Two cat
Dog 0
Dog 2
How to write a selector in CSS (no jQuery, no JS available) to make those texts bold?
To select all p elements inside a div element, you can use the descendent selector. The descendant selector allows you to select and style all descendants of an element. To select all the descendants of an element, you have to simply put white space between the parent and the child. For example, div p , ul li , etc.
Use the CSS :nth-last-of-type(n) selector to select every <p> element that is the second <p> element of its parent, counting from the last child.
If you're willing to branch into CSS3, the first-of-type selector is exactly what you're trying to accomplish. first-of-type will always select the first occurrence of an element at any level. So for your case, it would style the first <h2> at any level in the markup tree.
You can do this by using the css ~
selector, followed by the nth-of-type
(alternatively nth-child
) selector. You can read more about it these selectors on the MDN: General Sibling Selector and :nth-of-type.
And here's how to achieve what you wanted. Essentially, you're selecting all odd <p>
elements that are siblings (i.e that come after) an <h2>
tag.
h2 ~ p:nth-of-type(odd) {
font-weight: 600;
}
<div>
<h2>This is a title cat</h2>
<p>This is a message</p>
<p>One cat</p>
<p>Two cat</p>
<p>Three cat</p>
<h2>This is a title dog</h2>
<p>Dog 0</p>
<p>Dog 1</p>
<p>Dog 2</p>
<p>Dog 3</p>
</div>
h2 ~ p:nth-of-type(2n+1){
font-weight: 600;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With