为什么这个 CSS :first-child 选择器不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7589841/
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
Why doesn't this CSS :first-child selector work?
提问by Alex Moore
I'm working on an Asp.Net MVC 3 project and have run into a brick wall on why this doesn't work like I think it should.
我正在研究一个 Asp.Net MVC 3 项目,但遇到了一个问题,为什么这不像我认为的那样工作。
My markup is:
我的标记是:
<fieldset>
<input type="hidden" value="2">
<div class="editor-label">
<label for="Name"> Name</label>
</div>
...
</fieldset>
My css is:
我的CSS是:
.display-label, .editor-label
{
margin: 0.8em 0 0 0;
font-weight: bold;
display: inline;
}
fieldset > div:first-child
{
margin: 0;
}
All I want to do is make the first div in the fieldset have a margin of 0. I thought that the selector fieldset > div:first-child
would apply the style to "the first child of a fieldset, whose type is a div", but apparently something is eluding me.
我想要做的就是使字段集中的第一个 div 的边距为 0。我认为选择器fieldset > div:first-child
会将样式应用于“字段集的第一个子项,其类型为 div”,但显然有些东西在逃避我.
I've tried this in IE9/FF/Chrome so it's not an old browser messing with my selectors.
我已经在 IE9/FF/Chrome 中尝试过这个,所以它不是一个旧的浏览器弄乱了我的选择器。
Thanks.
谢谢。
回答by thirtydot
fieldset > div:first-child
means "select the first child element of a fieldset
ifit's a div
".
fieldset > div:first-child
意思是“选择 a 的第一个子元素,fieldset
如果它是 a div
”。
It does not mean "select the first div
in the fieldset
".
这并不意味着“选择第一个div
在fieldset
”。
The first child in this case is <input type="hidden" value="2">
.
在这种情况下,第一个孩子是<input type="hidden" value="2">
。
To select that div
without changing the HTML, you need to use fieldset > div:first-of-type
.
要在div
不更改 HTML 的情况下选择它,您需要使用fieldset > div:first-of-type
.
Unfortunately, while :first-child
is widely supported, :first-of-type
only works in IE9+ and other modern browsers.
不幸的是,虽然:first-child
被广泛支持,但:first-of-type
仅适用于 IE9+ 和其他现代浏览器。
So, in this case, the best fix is to continue using fieldset > div:first-child
, and simply move <input type="hidden" value="2">
so that's it's not the first child.
因此,在这种情况下,最好的解决方法是继续使用fieldset > div:first-child
,然后简单地移动,<input type="hidden" value="2">
这样它就不是第一个孩子。