【问题标题】:How to select childs in CSS如何在 CSS 中选择孩子
【发布时间】:2021-10-26 16:38:00
【问题描述】:

我有一个导航列表,想在导航项前面放置一个图标,所以我这样做了,但它会将相同的图标放在所有导航项上。

如何选择 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;
}

【问题讨论】:

  • 没有看到您的 HTML 结构,我们只能猜测。请把它放在你的问题中。值得我猜的是,您的物品都是他们各自父母的第一个孩子,所以您每次都得到第一个 img。

标签: css css-selectors html-lists


【解决方案1】:

为了给你一个正确的答案,看看你的 HTML 代码会很好。 您可以使用 :nth 选择器选择特定的孩子。

ul {
    list-style: none;
}
li:nth-child(1):before {
    content: '1';
}
li:nth-child(2):before {
    content: '2';
}
li:nth-child(3):before {
    content: '3';
}
li:nth-child(4):before {
    content: '4';
}
<ul>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
  <li>List item 4</li>
</ul>

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 为什么不把两个答案放在同一个答案中?
    • 这样做是最佳做法吗?我不确定。
    • 一般来说我会说是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多