我想在顶层li
实现一个简单的放大字体加边框加背景的效果列表的元素,而不影响较低的嵌套级别(子列表)。这四个问题和答案是相关的,但不要回答我下面的问题。
Target first level <li>s and not the nested <li>s
Style first level of menu only
Style only first level of unordered list
styling a nested list in CSS
这是最小的例子:
ol.toplevel > li {
font-size: 160%;
margin-bottom: 0.5em;
margin-top: 1.5em;
padding-bottom: 0.2em;
padding-top: 0.1em;
}
ol.toplevel div.topleveltitle {
background-color: yellow;
border-bottom: 1px solid red;
border-top: 1px solid red;
color: red;
}
ol.toplevel li li {
/*For lower nested levels, we don't want to inherit any top-level settings*/
all: revert; /*does not seem to work at all, "unset" neither*/
font-size: 70%; /*undo 160%, but we don't want to propagate 70% to lower levels!*/
}
<ol class="toplevel">
<li><div class="topleveltitle">First title</div></li>
<li><div class="topleveltitle">Second title</div>
<ol>
<li>Subitem</li>
<li>Subitem</li>
<li>Subitem</li>
<li>Subitem</li>
</ol>
</li>
<li>Third title
<ul>
<li>Subitem
<ol>
<li>Subsub</li>
<li>Subsub</li>
</ol>
</li>
</ul>
</li>
</ol>
经过这么多年的 css 开发,我希望这个简单的目标能够以一种简单、简洁和优雅的方式实现——没有技巧、黑客和冗余。所以这里是关于这个例子的具体问题:
- 是否可以避免引入助手
<div>
或<span>
连同topleveltitle
, 并使用 css 仅为顶级<ol>
定义样式影响每个顶级<li>
文本而不影响嵌套子列表的内容?如果</li>
会起作用关闭标记紧跟在标题之后,但这样它就无效了,因为根据 html 规范,关闭标记必须放置在嵌套子列表之后,如示例中所示。 - 是否可以通过一种可能简单的方式将颜色背景和边框扩展到列表项编号?
- 是否有可能避免所有这些防止样式从顶级嵌套继承到较低嵌套级别的复杂性? “恢复”不按使用方式工作,我不想明确枚举和设置在顶层修改的所有属性以用于较低级别,特别是考虑到它们的值可能是未知的,因为它们本身可能是继承的或依赖于用户/浏览器设置。我宁愿只影响顶级,而不是影响所有级别,然后枚举异常或重新定义较低级别的值。
最佳答案
实现是否实现了您想要做的事情?
ol {
counter-reset: my-awesome-counter;
}
ol li {
font-size: 1rem;
color: black;
list-style: none;
counter-increment: my-awesome-counter;
}
ol li::before {
content: counter(my-awesome-counter) ". ";
width: 2rem;
}
ol.toplevel > li::before {
background-color: yellow;
border-bottom: 1px solid red;
border-top: 1px solid red;
color: red;
}
ul > li::before {
content: ''
}
ol.toplevel > li {
font-size: 1.8rem;
margin-bottom: 0.5em;
margin-top: 1.5em;
padding-bottom: 0.2em;
padding-top: 0.1em;
}
ol.toplevel > li span {
display: inline-block;
width: calc(100% - 2rem);
background-color: yellow;
border-bottom: 1px solid red;
border-top: 1px solid red;
color: red;
}
<ol class="toplevel">
<li><span>First title</span></li>
<li><span>Second title</span>
<ol>
<li>Subitem</li>
<li>Subitem</li>
<li>Subitem</li>
<li>Subitem</li>
</ol>
</li>
<li><span>Third title</span>
<ul>
<li>Subitem
<ol>
<li>Subsub</li>
<li>Subsub</li>
</ol>
</li>
</ul>
</li>
</ol>
它通过添加计数器并隐藏默认编号来使用自定义列表编号。
关于html - 仅对嵌套列表的第一级设置样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59013197/