css - 如何在 CSS 中选择孩子
问题描述
我有一个导航列表,想在导航项前面放置一个图标,所以我这样做了,但它在所有导航项上都放置了相同的图标。
如何选择 1、2、3 和 4 导航项并在 CSS 中为每个导航项放置不同的导航图标?
它不起作用,仍然显示第一个图标,而不是 2,3 和 4。
.shop-menu .mobile-nav__link:nth-child(1)::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 2em;
height:100%;
background: url("/files/NewArrivalsIcon.png?v=1635225557") no-repeat center center transparent;
background-size: contain;
}
.shop-menu .mobile-nav__link:nth-child(2)::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 2em;
height:100%;
background: url("files/AnimalPrintsIcon.png?v=1635225557") no-repeat center center transparent;
background-size: contain;
}
.shop-menu .mobile-nav__link:nth-child(3)::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 2em;
height:100%;
background: url("files/Under500Icon.png?v=1635225557") no-repeat center center transparent;
background-size: contain;
}
.shop-menu .mobile-nav__link:nth-child(4)::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 2em;
height:100%;
background: url("files/NewArrivalsIcon.png?v=1635225557") no-repeat center center transparent;
background-size: contain;
}
解决方案
是的,您可以为每个导航项设置唯一的 ID,这是一个示例。
#item1::before {
content:'1'
}
#item2::before {
content:'2'
}
<ul>
<li id="item1"></li>
<li id="item2"></li>
</ul>
解决方案#2
您还可以使用第 n 个子选择器。
但是,请记住,“顺序”取决于包括所有元素在内的整体顺序。因此,例如,如果您有一个包含 2 个 img 元素和 1 个 p 元素的 div,按以下顺序:
<div>
<p>
<img>
<img>
</div>
然后选择最后一张图片,您将使用 nth-child(3) (不是 2 用于第二张图片)。
推荐阅读
- r - 需要编译的包不能用不同的名字安装
- python - 我无法使用 python 从 JSON 获取数据
- arrays - 转换数组以显示在列表中
- android - 如何从上下文菜单启动 Intent
- docker - Hyperledger Fabric 原生设置和 Hyperledger Fabric Docker 版本设置之间的区别?
- r - 使用 str_detect 和 dplyr 创建分组类别
- python - 在 Python 中执行 Dunnett 的多重比较测试
- r - 使用 stringr::str_detect 和 grepl 的 R 正则表达式在被“\\b”包围时似乎不匹配“\\+”
- django - 通过中间模型保存多对多关系
- cordova - Cordova Plugin inappbrowser : 如何在 Cordova Webview 中使用 Cordova?