CSS CSS3 伪类不是第一个和最后一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16830761/
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
CSS3 pseudo class not first and last child
提问by haind
I have some following HTML code:
我有一些以下 HTML 代码:
<ul>
<li>number 1</li>
<li>number 2</li>
<li>number 3</li>
<li>number 4</li>
<li>number 5</li>
<li>number 6</li>
<li>number 7</li>
<li>number 8</li>
<li>number 9</li>
<li>number 10</li>
</ul>
How can I use CSS3 pseudo-classes to make any li
element which is not the first or last have a background-color
of tomato
for example? It seems that I could use the :not
selector.
例如,如何使用 CSS3 伪类使任何li
不是第一个或最后一个元素的元素具有background-color
of tomato
?看来我可以使用:not
选择器。
回答by Nick Andriopoulos
Two ways :
两种方式:
you can set a generic rule, and then override it for :first-child
and :last-child
items. This plays to CSS strengths:
您可以设置通用规则,然后为:first-child
和:last-child
项目覆盖它。这发挥了 CSS 的优势:
li { background: red; }
li:first-child, li:last-child { background: white; }
Or, you can use the :not
keyword combined combining the two:
或者,您可以使用:not
关键字组合将两者结合起来:
li { background: white; }
li:not(:first-child):not(:last-child) { background: red; }
Of the two, I personally prefer the first - it's easier to comprehend and maintain (in my opinion).
在这两者中,我个人更喜欢第一个——它更容易理解和维护(在我看来)。
回答by Alessandro Vendruscolo
Here's a pen http://codepen.io/vendruscolo/pen/AeHtG
这是一支笔 http://codepen.io/vendruscolo/pen/AeHtG
You have to combine two :not()
pseudo classes:
你必须结合两个:not()
伪类:
li:not(:first-child):not(:last-child) {
background: red;
}
Here's the MDN documentation: as stated there, it's not supported on IE < 9, while it's well supported on other browsers.
这是MDN 文档:如上所述,它在 IE < 9 上不受支持,而在其他浏览器上得到很好的支持。
If you need IE 8 support, you have to rely on Javascript or use another class to indicate which element is the last child. In fact, IE 8 (and lower) doesn't support the :last-child
pseudo class.
如果您需要 IE 8 支持,则必须依赖 Javascript 或使用另一个类来指示哪个元素是最后一个子元素。事实上,IE 8(及更低版本)不支持:last-child
伪类。