Css selectors: finding the last sibling of a type

I have a document that looks like this:

<h1>Title A</h1>
<h2>Sub 1</h2>
<h1 class='foo'>Title B</h1>
<h2>Sub 2</h2>
<h2>Sub 3</h2>
<h1>C</h1>
<h2>Sub 4</h2>

      

And I would like to select Sub 2 and 3 because they are after Title B, h1 with class foo. However, Sub 4 doesn't interest me because the previous h1 has a class foo.

I know I can put a div around each block starting at h1, but my content is generated with markdown, so the only way is to change the DOM after the page has loaded and it feels messy and cumbersome.

My question is related to this How to select all elements after a certain element in CSS , but I am missing the "back to normal" behavior once a normal h1 is seen.

+3


source to share


2 answers


You can use a generic sibling selector ~

to select tags <h2>

after <h1>

with the class .foo

and use it again to "reset" CSS properties after the following tag <h1>

:



.foo ~ h2 {
  color: red;
}
.foo ~ h1 ~ h2 {
  color: black;
}
      

<h1>Title A</h1>
<h2>Sub 1</h2>
<h1 class='foo'>Title B</h1>
<h2>Sub 2</h2>
<h2>Sub 3</h2>
<h2>Sub 4</h2>
<h2>Sub 5</h2>
<h1>C</h1>
<h2>Sub 6</h2>
<h2>Sub 7</h2>
      

Run code


This example will change the color of all h2 tags after the element .foo

(which means you can have as much as you want) and reset to black after the next tag h1

.

+1


source


http://jsfiddle.net/70zxd3h8/

.foo + h2, .foo + h2 + h2 {
    background:red;
}

      



Or h2: nth-of-type (2), h2: nth-of-type (3)

+4


source







All Articles