CSS 选择第二个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9550401/
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
select second child
提问by Ryan Durrant
I am trying to use this to select the second a tag from a list:
我正在尝试使用它从列表中选择第二个 a 标签:
.container li a:first-child + a { ... }
but it doesn't seem to work. Is there another, ideally pure CSS way (other than a:nth-child(2)
) or can anyone see where I have gone wrong?
但它似乎不起作用。是否有另一种理想的纯 CSS 方式(除了a:nth-child(2)
),或者任何人都可以看到我哪里出错了?
回答by BoltClock
Make sure your <li>
actually has two <a>
elements as its first two children, and not some other elements around them since those may be invalidating the :first-child
and adjacent sibling selectors.
确保您的前两个子元素<li>
实际上有两个<a>
元素,而不是它们周围的其他元素,因为这些元素可能会使:first-child
相邻的同级选择器无效。
If you just want to select the second <a>
element regardless of what other types of elements there are in your <li>
, use this selector:
如果您只想选择第二个<a>
元素而不管您的 中有哪些其他类型的元素,请<li>
使用此选择器:
.container li a:nth-of-type(2)
If your <li>
will only have exactly 2 <a>
elements, you can use the general sibling combinator ~
for bonus IE7/IE8 support:
如果您<li>
只有 2 个<a>
元素,您可以使用一般的兄弟组合器~
来获得额外的 IE7/IE8 支持:
.container li a ~ a
Or did you mean to find the <a>
element in the second <li>
rather than the second <a>
element in a <li>
(since "list" probably refers to <ul>
or <ol>
here)? If so, you'll want either of these selectors:
或者你的意思是<a>
在第二<li>
个<a>
元素中找到元素而不是在 a 中的第二个元素<li>
(因为“列表”可能指的是<ul>
或<ol>
这里)?如果是这样,您将需要以下任一选择器:
.container li:first-child + li a
.container li:nth-child(2) a
回答by NGLN
I suspect your anchors are within list items:
我怀疑您的锚点在列表项中:
<ul class="container">
<li><a href="">...</a></li>
<li><a href="">...</a></li>
<li><a href="">...</a></li>
</ul>
In that case, you have to rewrite the style to:
在这种情况下,您必须将样式重写为:
.container li:first-child + li a { ... }
回答by Ry-
Just use :nth-of-type
:
只需使用:nth-of-type
:
.container li a:nth-of-type(2) {
/* ... */
}
The problem here is probably that the first <a>
is not the first child, or the second <a>
is not adjacent to it. Regardless, :nth-of-type
is the right way to do it.
这里的问题可能是第一个<a>
不是第一个孩子,或者第二个<a>
与它不相邻。无论如何,这:nth-of-type
是正确的方法。
If you have one <a>
per <li>
, then you probably mean .container li:nth-of-type(2) a
.
如果你有一个<a>
每次<li>
,那么你就可能意味着.container li:nth-of-type(2) a
。
回答by devsam247
Use nth-child(2)
使用 nth-child(2)
.container li a:nth-child(2){....}