我有这样的内容:
<div class="content">
<div class="row">
<h1>foo1</h1>
</div>
<div class="row">
<a href="#">foo11</a>
</div>
<div class="row">
<a href="#">foo12</a>
</div>
<div class="row">
<h1>foo2</h1>
</div>
<div class="row">
<a href="#">foo21</a>
</div>
</div>
如何选择 h1 标签 foo1 和 foo2 之间的链接?
我已经尝试过这个:
.content .row > :not(h1) a
但这选择:
<a href="#">foo11</a>
<a href="#">foo12</a>
<a href="#">foo21</a>
我想要的是:
<a href="#">foo11</a>
<a href="#">foo12</a>
此外,包含 h1
的行后面的 div.row
的数量是可变的。
最佳答案
您本质上有一个层次结构,但在 HTML 中并未以层次结构形式表示。最好的解决方案是在 HTML 中添加另一个级别来表示层次结构。
如果您无法做到这一点,并且无法使用此 HTML,那么您可以尝试使用 sibling combinators ,但无论如何,您都需要某种方法来解决 foo1
和foo2
元素。这可能是一个类,或者 nth-child
如果您知道顺序、数据属性或其他任何内容。这不可能是<h1>
上的东西。元素,因为 CSS 没有提供“向上和越过”的方式。这一定是一种解决更高级别问题的方法row
包含 h1
的元素。在下面,我假设您有一个可用的类(class)。在这种情况下:
/* Make everything after `foo1` red. */
.foo1 ~ .row a { color: red; }
/* But make `foo2` and everything after it the original color. */
.foo2.row a, .foo2 ~ .row a { color: inherit; }
<div class="content">
<div class="row foo1">
<h1>foo1</h1>
</div>
<div class="row">
<a href="#">foo11</a>
</div>
<div class="row">
<a href="#">foo12</a>
</div>
<div class="row foo2">
<h1>foo2</h1>
</div>
<div class="row">
<a href="#">foo21</a>
</div>
</div>
关于html - 如何选择子元素直到找到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601213/