html - 如何选择子元素直到找到元素

标签 html css css-selectors

我有这样的内容:

<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 ,但无论如何,您都需要某种方法来解决 foo1foo2元素。这可能是一个类,或者 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/

相关文章:

css - 我可以合并 :nth-child() or :nth-of-type() with an arbitrary selector? 吗

html - 使用 CSS 的字段集 HTML 样式

javascript - 如何使用 HTML 和 CSS 模拟从图像/div 到另一个图像/div 的光线

html - 嵌套 div 的背景颜色

html - Wordpress 对齐问题

CSS nth-child 1-6、7-12 等

css - 这是什么类型的 CSS 选择器?这是什么意思?

python - 隔离标题和文本 BeautifulSoup

javascript - 使用 jQuery 禁用悬停效果调整大小

html - 如何为 input 和相邻的 inline-block 元素设置相同的行高?