Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style every odd p element after h2 element occured in css?

Tags:

html

css

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?

like image 991
Tom Smykowski Avatar asked May 24 '16 08:05

Tom Smykowski


People also ask

How do you select all p elements that appear after a div element?

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.

How do you select the second p element in CSS?

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.

Which CSS selector can be used here to give style to the first h2 element?

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.


2 Answers

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>
like image 188
Chris Avatar answered Nov 15 '22 06:11

Chris


h2 ~ p:nth-of-type(2n+1){
font-weight: 600;
}
like image 40
masawa Avatar answered Nov 15 '22 06:11

masawa