gpt4 book ai didi

css - 如何在嵌套元素之后选择紧接的下一个元素?

转载 作者:行者123 更新时间:2023-12-04 03:25:27 25 4
gpt4 key购买 nike

我需要将样式应用到紧接在两个嵌套无序列表之后的段落。我知道在一个 ul 之后立即将样式应用于段落的方法是:

.class ul+p 

但我无法弄清楚如何将其缩小到仅在两个嵌套的 ul 之后才生效?这就是我尝试这样做的方式,但它不起作用:

.class ul ul + p 

代码示例:

.class ul + p {
color:red;
}

.class ul ul {
color:purple;
}

/* This is just an example of what I tried, does not work */
.class ul ul + p {
color:green;
}
<div class="class">
<ul>
<li>Item a</li>
<li>Item b
<ul>
<li>Item c (Nested list, CSS for this works fine)</li>
<li>Iten d (should be purple)</li>
</ul>
</li>
</ul>
<p>Paragraph after nested ul, this is the one I can't get to work,
what kind of CSS would I need? (should be green)</p>
<ul>
<li>item e</li>
<li>item f</li>
</ul>
<p>Paragraph after single ul, CSS for this works fine (should be red)</p>
</div>

最佳答案

ul ul + p 不起作用,因为该段落是第一个 ul 的同级段落。

嵌套的 ul 是第一个 ul 的后代,不是 p 的兄弟。因此,下一个兄弟组合器 (+) 无法按预期运行。

<ul><!-- top level ul; sibling of the parapraph element -->
<li>Item a</li>
<li>Item b
<ul><!-- nested ul; not a sibling of the parapraph element -->
<li>Item c (Nested list, CSS for this works fine)</li>
<li>Iten d (should be purple)</li>
</ul>
</li>
</ul>
<p>Paragraph after nested ul, this is the one I can't get to work,
what CSS would I need? (should be green)</p><!-- sibling of the top level ul -->

对于纯 CSS 解决方案,您需要类似 :has() 的东西伪类。选择器可能如下所示:

ul:has(> ul) + p

不幸的是,:has()not yet supported by any major browsers .

那么,试试 JavaScript。

关于css - 如何在嵌套元素之后选择紧接的下一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67696847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com