CSS深层嵌套的:last-child选择器

huangapple go评论56阅读模式
英文:

CSS deeply nested :last-child selector

问题

我正在处理一些HTML组件,基本上想在特定类上设置:last-child选择器。问题是,这个类深度嵌套在我想要在其上使用选择器的父类中,因此当我使用last-child时,它会影响所有组件的CSS。我遇到的一个问题是,我想要更改CSS的选择器嵌套在不同的组件中。

这是我尝试过的示例:

parent .my-class:last-child {
  border-bottom: none;
}
parent > * > .my-class:last-child {
  border-bottom: none;
}

这是HTML的样子:

<parent>
  <a>
    <div class="my-class"></div>
  </a>
  <b>
    <div class="my-class"></div>
  </b>
  <c>
    <div class="my-class"><div>
  </c>
  <d>
    <div class="my-class"></div>
  </d>
</parent>
... 更多父元素和更多子元素,可以是任何内容,并嵌套更多的.my-class元素

我的CSS发生的情况是它们都被识别为:last-child。我希望发生的是只有完整的选择器parent > d > .my-class 被识别为最后一个子元素。

请记住,这些元素的顺序不总是相同的,所以使用我提供的选择器对我的情况不起作用。

这是一个codepen示例

英文:

I am working with some html components and I basically want to set a :last-child selector on a specific class. The issue is that the class is deeply nested within the parent class that I want to use the selector on so when I use last child it is affecting the css for all of the components. One of the issues I am running into is that the selctor I want to change the css for is nested in different components.

Here is an example of what I tried:

parent .my-class:last-child {
  border-bottom: none;
}
parent > * > .my-class:last-child {
  border-bottom: none;
}

Here is what the HTML looks like:

<parent>
  <a>
    <div class="my-class"></div>
  </a>
  <b>
    <div class="my-class"></div>
  </b>
  <c>
    <div class="my-class"><div>
  </c>
  <d>
    <div class="my-class"></div>
  </d>
</parent>
... more parents with more children elements that can be whatever and nest more .my-class elements

What is happening wiht my css is that they are all being recognized as the :last-child. What I want to happen is only the full selector parent > d > .my-class to be recognized as the last child.

Keep in mind that the elements are not always in the same order so using the selector I provided above will not work for my case.

Here is a codepen exmple.

答案1

得分: 1

问题在于我将:last-child选择器放在了选择器中的错误元素上。正确的选择器应该是:

parent > *:last-child .my-class {
  border-bottom: none;
}

这个 codepen 已经更新,以包含使其正常工作所需的正确 CSS。

英文:

The issue was that I was putting the :last-child selector on the wrong element in the selector. The correct selector should be:

parent > *:last-child .my-class {
  border-bottom: none;
}

The codepen has been updated with the correct css needed to make it work.

huangapple
  • 本文由 发表于 2023年3月4日 03:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630925.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定