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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:24:11  来源:igfitidea点击:

first-child not working

csscss-selectors

提问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-childworks fine, research:first-childdoesn'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-childonly 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-classpseudo-class. If you are looking to apply styles to the first of each class of your divelements, 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-childpseudo-class represents an element that is the first child of some other element.

一样:nth-child(1)。该:first-child伪类表示一些其他元素的第一个子元素。

.project.researchis 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';}

Updated fiddle

更新的小提琴

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-childif it may not be a pelement, you could use *:first-childinstead.

这第一个孩子相匹配与类“项目”和“工作”(或“项目”和“研究”)的元素。您没有使用p:first-child,如果它可能不是一个p元素,你可以使用*:first-child来代替。