首页 > 解决方案 > 如何在 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;
}

标签: csscss-selectorshtml-lists

解决方案


是的,您可以为每个导航项设置唯一的 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 用于第二张图片)。


推荐阅读