【发布时间】:2022-02-02 17:24:36
【问题描述】:
有没有更好的写法:
#container ul ul ul
我需要定位第三个嵌套列表以及之后的所有其他嵌套列表吗?
【问题讨论】:
-
“更好”究竟如何?
-
你应该包括一个你正在使用的标记的例子,以更好地阐明你的问题和你得到的答案,以及可能在描述你希望达到的结果的图像中
有没有更好的写法:
#container ul ul ul
我需要定位第三个嵌套列表以及之后的所有其他嵌套列表吗?
【问题讨论】:
您可以通过多种方式做到这一点。如果您只是想从第三个 ul 元素向上分配一个 css 属性(即:3 ul、4 ul、n ul),最简单的方法是使用星号 *。
#container ul ul > * {
font-style: italic
}
我在下面的例子中使用了几个选择器。您实际使用哪一个取决于您。
#container ul ul ul {
color: green;
}
div ul > ul > ul {
font-size: 30px;
}
.third {
text-decoration: underline;
}
#container ul ul > * {
font-style: italic;
font-weight: bold;
}
blockquote {
color: gray;
}
<blockquote>I need to target the third nested list and every other one after that?
</blockquote>
<div id="container">
<ul>
<li>1 ul</li>
<ul>
<li>2 ul</li>
<ul class="third">
<li>3 ul</li>
<ul class="third">
<li>4 ul</li>
<ul>5 ul</ul>
</ul>
</ul>
</ul>
</ul>
</div>
【讨论】:
#container ul ul * 这适用于哪个 ul?第三?第四还是全部?
#container ul ul > * 并且从 2 开始应用 css 属性。我在回答中包含了工作示例。
也许在 css 中使用> 选择器或为元素分配className,但我认为没有比这两种方法更简单的方法了。
使用>,会直接指定父元素(例如B)的子元素(例如A),不会选择A的追加子元素。
在此处查看更多信息:What is the difference between '>' and a space in CSS selectors?
您正在尝试获取嵌套的ul,因此nth-of-child 或nth-of-type 之类的内容对您不起作用。
#ul>ul>ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
Yes
</ul>
</ul>
</ul>
对 css 中空格和> 的区别感到困惑?
检查这个作为例子:
#ul>ul>ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
This will be considered
</ul>
<div>
<ul>This will not be considered</ul>
</div>
</ul>
</ul>
#ul ul ul {
background: red
}
<ul id='ul'>
<ul>
<ul>
This will be considered
</ul>
<div>
<ul>This will be considered as well</ul>
</div>
</ul>
</ul>
【讨论】:
> 之间的区别。虽然> 看起来与 CSS 中的空格几乎相同,但它们是一种更安全/更好的方式,特别是当您想要选择特定的子元素时。查看更多:stackoverflow.com/questions/2636379/…
A B 中的样式适用于 B,即使 B 是 A 的第二个后代,但在 A > B 中不适用?
> 仅指定直接子元素而不是任何后代(包括孙子、孙子等),但是空间会做
其他答案似乎忽略了您的其他标准,即:'以及之后的所有其他标准'
这回答了这个问题
#content ul ul ul:first-of-type,
#content ul ul ul ~ ul:nth-of-type(odd) { color: green;}
<div id="content">
<ul>
<li>one</li>
<ul>
<li>two</li>
<ul>
<li>three.1</li>
</ul>
<ul>
<li>three.2</li>
</ul>
<ul>
<li>three.3</li>
</ul>
<ul>
<li>three.4</li>
</ul>
<ul>
<li>three.5</li>
</ul>
</ul>
</ul>
</div>
是的,它看起来很乱的 css(不是真的,恕我直言,而是每个人自己的),但如果您无权向标记添加类,这就是方法。
【讨论】: