我如何样式的元素不添加类或id到我的HTML?



我希望能够操纵<li>F</li>而不添加id或类?有办法吗?是否可以改变它的背景颜色,只是用下面的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>

最新更新