CSS 如何选择除最后一个子元素之外的元素的所有子元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 21:51:46  来源:igfitidea点击:

How can I select all children of an element except the last child?

css-selectorscss

提问by RyanScottLewis

How would I select all but the last child using CSS3 selectors?

我将如何使用 CSS3 选择器选择除最后一个孩子之外的所有孩子?

For example, to get only the last child would be div:nth-last-child(1).

例如,要仅获取最后一个孩子将是div:nth-last-child(1)

回答by Nick Craver

You can use the negation pseudo-class :not()against the :last-childpseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:

您可以使用否定伪类:not():last-child伪类。引入 CSS Selectors Level 3,它在 IE8 或更低版本中不起作用:

:not(:last-child) { /* styles */ }

回答by Sebastien Horin

Make it simple:

让它变得简单:

You can apply your style to all the div and re-initialize the last one with :last-child:

您可以将您的样式应用于所有 div 并使用:last-child重新初始化最后一个:

for example in CSS:

例如在CSS 中

.yourclass{
    border: 1px solid blue;
}
.yourclass:last-child{
    border: 0;
}

or in SCSS:

或在SCSS 中

.yourclass{
    border: 1px solid rgba(255, 255, 255, 1);
    &:last-child{
        border: 0;
    }
}
  • easy to read/remember
  • fast to execute
  • browser compatible(IE9+ since it's still CSS3)
  • 易于阅读/记忆
  • 执行速度快
  • 浏览器兼容(IE9+,因为它仍然是 CSS3)

回答by Robin B

Nick Craver's solution works but you can also use this:

Nick Craver 的解决方案有效,但您也可以使用它:

:nth-last-child(n+2) { /* Your code here */ }

Chris Coyier of CSS Tricks made a nice :nth testerfor this.

CSS Tricks 的 Chris Coyier 为此做了一个不错的:nth 测试器

回答by Nicholas Wilson

When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).

等IE9来了,就容易多了。但是,很多时候,您可以将问题切换到需要 :first-child 并设置元素另一侧的样式 (IE7+)。

回答by delphi

Using nick craver's solution with selectivizrallows for a cross browser solution (IE6+)

使用带有selectivizr 的nick craver 的解决方案允许跨浏览器解决方案 (IE6+)

回答by Avinash Malhotra

to find elements from last, use

从最后查找元素,使用

<style>
ul li:nth-last-of-type(3n){ color:#a94442}  /**/
</style>

回答by maddRobot

Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:

Nick Craver 的解决方案给了我我需要的东西,但让那些使用 CSS-in-JS 的人明确:

const styles = {
  yourClass: {
    /* Styles for all elements with this class */
    '&:not(:last-child)': {
      /* Styles for all EXCEPT the last element with this class */
    },
  },
};

回答by RyanGonzalezUSA

.nav-menu li:not(:last-child){
    // write some style here
}

this code should apply the style to all

此代码应将样式应用于所有

  • except the last child

  • 除了最后一个孩子