gpt4 book ai didi

css - 为任意深度的嵌套列表设置样式

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

我想知道是否可以在不使用任何脚本的情况下仅使用 CSS 设置嵌套无序列表的样式。问题在于 CSS 需要适用于列表树的任何深度。

例如,我有一个列表:

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li class="holder">
<ul>
<li>Item 4</li>
<li>Item 5</li>
<li class="holder">
<ul>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li class="holder">
<ul>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

这是我的 CSS:

li{
background: gray;
border: 1px solid;
display: block;
margin: 2px;
}
.holder{
background: none;
border: none;
}

/*replace these styles*/
li > ul > li{
background: white;
}

li > ul > li > ul > li{
background: gray;
}

li > ul > li > ul > li > ul > li{
background: white;
}

如果节点的父节点有背景A,节点应该有背景B。如果节点的父节点有背景B,节点应该有背景A。

请检查:http://jsfiddle.net/bCU34/6/

最佳答案

CSS 选择器允许您通过使用空格将命名元素与父元素分隔开来选择父节点的所有 命名元素。例如,要选择所有无序列表元素,您可以像下面那样做。注意 任何深度 的所有 ul 元素都继承无元素符号/边距/填充的样式。为了为元素类型设置 nth 层的样式,您需要使用父选择器 >。见下文。我使用了字体颜色,但你可以用同样的方式设置背景图片。请注意,据我所知,此时没有后代级别选择器。这在另一篇文章中得到了解决 CSS select nested elements up to N levels deep .

.container ul {
list-style-type: none;
margin: 0;
padding: 0;
}

.container > ul > li {
color: green;
}
.container > ul > li > ul > li {
color: red;
}
.container > ul > li > ul > li > ul > li {
color: blue;
}
<section class="container">
<h1>CSS Nested List Styling</h1>
<ul>
<li>
<h3>Section 1</h3>
<ul>
<li>
<h4>Foo</h4>
<ul>
<li>
<h5>Bar</h5>
</li>
<li>
<h5>Bar</h5>
</li>
</ul>
</li>
<li>
<h4>Foo Bar</h4>
<ul>
<li>
<h5>Bar</h5>
</li>
<li>
<h5>Bar</h5>
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3>Section 2</h3>
<ul>
<li>
<h4>Hello</h4>
<ul>
<li>
<h5>World</h5>
</li>
</ul>
</li>
</ul>
</li>
</ul>

</section>

关于css - 为任意深度的嵌套列表设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22270407/

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