如何将 CSS 应用于第 n 个嵌套元素?

How to apply CSS to nth nested element?

我的 HTML 中有这个结构,我正在尝试将一些 css 应用于 class target 的最后一个元素,但我不能'不知道如何去做或是否可能。似乎当我尝试 :last-child:last-of-type 之类的东西时,它只是将 css 应用于所有目标元素,因为它认为它们是唯一的元素。

<div className="parent"> 
  <div>
    <div className="target"></div>
  </div>
  <div>
    <div className="target"></div>
  </div> 
  <div>
    <div className="target"></div>
  </div>
</div>

如果你想应用 CSS last-child 那么你可以试试这个代码: 您可以为每个 div

添加 class
.parent div:nth-last-child(1) .target{
background: #000000;
color: #fff;
}

尝试类似的东西

.parent > div {
    width: 50px;
    height: 50px;

    border: solid 2px black;

    background-color: red
}
.parent div:last-child {
    background-color: blue
}

也许我知道你的代码发生了什么。写 .target:last-child 你 select 任何 div 元素 .target class 是另一个元素的最后一个子元素。您的 CSS 代码应用于每个 .target 元素,因为每个元素都嵌套在一个单独的 div 中,因此每个 .target div 都是最后一个(并且是唯一的) ) 中每个 div 的子项都是嵌套的。 所以要做你想做的事,试试这个 HTML:

<div class="parent">
        <div class="target"></div>
        <div class="target"></div>
        <div class="target"></div>

和这个 CSS:

.target {
    width: 100px;
    height: 100px;
    background-color: red;
    margin-top: 50px;
}

.target:last-child {
    background-color: blue;
}

请注意,如果您的项目中有另一个 div with .parent class 其中包含带有 .target class 的元素,则此 CSS 将被应用也对这些其他代码。如果您尝试多次复制和粘贴 HTML,您将能够明白我在说什么。 希望对您有所帮助!