CSS 第一个孩子不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8535686/
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
first-child not working
提问by uriah
Should this work am I going crazy?
这项工作应该让我发疯吗?
.project.work:first-child:before {
content: 'Projects';
}
.project.research:first-child:before {
content: 'Research';
}
<div class="project work">
<p>abcdef</p>
</div>
<div class="project work">
<p>abcdef</p>
</div>
<div class="project work">
<p>abcdef</p>
</div>
<div class="project research">
<p>abcdef</p>
</div>
projects:first-child
works fine, research:first-child
doesn't stick. Any ideas?
projects:first-child
工作正常,research:first-child
不粘。有任何想法吗?
DemoIt doesn't work, but whats the best way to achieve this?
演示它不起作用,但实现这一目标的最佳方法是什么?
采纳答案by BoltClock
:first-child
only selects the first child of its parent. Nothing else.
:first-child
只选择其父级的第一个子级。没有其他的。
As mentioned in a few of my other answers on the site (1234), there is no :first-of-class
pseudo-class. If you are looking to apply styles to the first of each class of your div
elements, a solution is to apply the styles to all children of that class, and a general sibling selector to undo the styles from subsequent siblings.
正如我在网站上的其他一些答案 ( 1 2 3 4) 中提到的,没有:first-of-class
伪类。如果您希望将样式应用于div
元素的每个类中的第一个,解决方案是将样式应用于该类的所有子项,并使用通用同级选择器来撤消后续同级元素的样式。
Your CSS would then look like this:
您的 CSS 将如下所示:
.project.work:before {
content: 'Work';
}
.project.research:before {
content: 'Research';
}
.project.work ~ .project.work:before,
.project.research ~ .project.research:before {
content: none;
}
回答by Felix Kling
From the specification:
从规范:
Same as
:nth-child(1)
. The:first-child
pseudo-class represents an element that is the first child of some other element.
一样
:nth-child(1)
。该:first-child
伪类表示一些其他元素的第一个子元素。
.project.research
is not the first child of its parent.
.project.research
不是其父母的第一个孩子。
回答by T.J. Crowder
I believe you want this CSS:
我相信你想要这个 CSS:
.project.work p:first-child:before {content:'Projects';}
.project.research p:first-child:before {content:'Research';}
or
或者
.project.work > p:first-child:before {content:'Projects';}
.project.research > p:first-child:before {content:'Research';}
That matches the first child ofan element with the classes "project" and "work" (or "project" and "research"). You don't have to use p:first-child
if it may not be a p
element, you could use *:first-child
instead.
这第一个孩子相匹配的与类“项目”和“工作”(或“项目”和“研究”)的元素。您没有使用p:first-child
,如果它可能不是一个p
元素,你可以使用*:first-child
来代替。