css - 添加第 8 个列表项时,仅使用 CSS 更改其他列表元素的属性
问题描述
我只使用 CSS 来设计一个列表。我希望在添加第 8 个 li 后更改所有列表项属性(通过在 HTML 中手动取消注释)。一旦我将其注释掉,列表项应恢复为各自的样式。
<body>
<div class="container">
<h1>Stylin' lists without adding classes</h1>
<h2>Do not change the HTML - edit only the CSS.</h2>
<ul class="silly-list">
<li>First item (and only first item) text is the $primary-accent color</li>
<li>Every item but the last has 13px padding</li>
<li>Even items in the list have a primary-color background color</li>
<li>Every third item has a square bullet point, not a round disc bullet point</li>
<li>The fifth list item text is orange</li>
<li>When you hover on this list item, the next list item directly below it will have its text color and/or background color turn a new color of your choice </li>
<li>EXTRA CHALLENGE (optional): At 8 list items and up (and only then), all list items change to have primary-accent color, white text, 10px padding all around, and a 1px solid white border! If there are 7 or fewer items, those styles don't apply. </li>
<!-- Uncomment this list item to have 8 items-->
<li>List item 8 here, when this list item is uncommented, write the CSS that will standardize the whole thing to blue and white</li>
</ul>
</div>
</body>
这是CSS:
// color variables for you to start with
$primary-color: papayawhip;
$primary-accent: lightseagreen;
.silly-list {
// write the css to make this list possible all nested here.
li:first-child {
color: $primary-accent;
}
> li:not(:last-child) {
padding: 13px;
}
li:nth-child(even) {
/* https://codepen.io/Paulie-D/pen/CBywn*/
background-color: #e3f3d4;
}
li:nth-child(3n+3) {
list-style-type: square;
}
li:nth-child(5) {
color: orange;
}
li:nth-child(6):hover + li {
color: red;
}
li:nth-child(-n+8){
background-color: $primary-accent;
color: white;
padding: 10px;
border: 1px solid white;
}
}
有问题的伪元素是li:nth-child(-n+8) {}
. 现在,它选择并将所有内容更改为li
8,这是有意义的。但是当我的列表中少于 8 个时,它不应该工作。
解决方案
诀窍是在第一个孩子也是倒数第二个孩子时选择第一个孩子。这有效地根据兄弟姐妹的数量进行选择。
li:first-child:nth-last-child(8),
li:first-child:nth-last-child(8) ~ li{
background-color: $primary-accent;
color: white;
padding: 10px;
border: 1px solid white;
}
推荐阅读
- python - 基于各种类型和对象属性的匹配
- javascript - 如何在codemirror中执行go group字符的命令?
- java - 无法理解 lambdas 和 longstream 方法
- r - 将数据框导出为 R 中单个 Excel 文件中的多个工作表
- oracle - 如何编写触发器来执行业务规则?
- python - 我为保存数据框编写了代码,但它工作不正确
- c++ - 2 个派生类的虚函数(十六进制 + 二进制)
- python - 在没有 \ 的情况下清理 JSON 字符串
- javascript - 如何让 Discord.js 机器人为每个用户记录变量
- docker - 容器中的 Go API 不返回任何响应