如何在不向我的 HTML 添加 class 或 id 的情况下设置元素样式?

How can i style an element without adding a class or id to my HTML?

我希望能够在不添加 id 或 class 的情况下操作 <li>F</li>? 有什么办法吗?是否可以仅使用下面的 HTML 代码更改它的背景颜色?警告:我不想更改剩余的 li

ul li {
  background-color: green; //Doing this, i am changing all of them
}
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="./styleA.css">
</head>
<body>
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
    <li>F</li>
  </ul>
</body>
</html>

您可以使用 last-childlast-of-type

ul li:last-child {
  background-color: green;
}

ul li:last-of-type {
  border: dotted  red
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
</ul>


其他可能的解决方案:

  • nth-last-child()/nth-last-of-type()
  • nth-child()/nth-last-of-type()

ul li:nth-last-child(1) {
  /* or nth-last-of-type(1) */
  background-color: green;
}


/*not recommended in this scenario if you want more items and always want to target last element*/

ul li:nth-child(6) {
  /* or nth-of-type(6) */
  border: dotted red
}
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
</ul>