如何解决如何在不向 HTML 中添加类或 id 的情况下设置元素样式?
我希望能够在不添加 ID 或类的情况下操作 <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-child
或 last-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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。