首页 > 解决方案 > 添加第 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) {}. 现在,它选择并将所有内容更改为li8,这是有意义的。但是当我的列表中少于 8 个时,它不应该工作。

标签: css

解决方案


诀窍是在第一个孩子也是倒数第二个孩子时选择第一个孩子。这有效地根据兄弟姐妹的数量进行选择。

    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;
    }

学分:http ://andr3.net/blog/post/142


推荐阅读