简体   繁体   English

css选择器:找到一个类型的最后一个兄弟

[英]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'd like to select Sub 2 and 3, because they are after Title B, a h1 with class foo. 我想选择Sub 2和3,因为它们位于Title B之后,是一个带有类foo的h1。 However, Sub 4 doen't interest me be cause the previous h1 is of class foo. 然而,Sub 4并不感兴趣,因为之前的h1属于foo类。

I know I could put div around each block beginning with h1, but my content is generated via markdown, so the only way is to change the DOM once the page is loaded, and it feels dirty and cumbersome. 我知道我可以在h1开头的每个块周围放置div,但我的内容是通过markdown生成的,所以唯一的方法是在页面加载后更改DOM,并且感觉很脏且很麻烦。

My question is kinda related to this one How to select all elements after specific element in CSS but I lack the "back to normal" behavior once a regular h1 is seen. 我的问题有点与此相关如何选择CSS中特定元素之后的所有元素,但是一旦看到常规的h1,我就缺乏“恢复正常”的行为。

http://jsfiddle.net/70zxd3h8/ http://jsfiddle.net/70zxd3h8/

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

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

You can use the general sibling selector ~ to select the <h2> tags after the <h1> with the class .foo and use it again to "reset" the CSS properties after the next <h1> tag : 您可以使用常规兄弟选择器 ~<h1>使用类.foo选择<h2>标记,并再次使用它来“重置”下一个<h1>标记后的CSS属性:

 .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> 

This example will change the color of all the h2 tags after the .foo element ( this means you can have as many as you want ) and reset it to black after the next h1 tag. 此示例将更改.foo元素之后所有h2标记的颜色( 这意味着您可以拥有任意数量 )并在下一个h1标记之后将其重置为黑色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM