:第一个孩子没有按预期工作

The*_*Man 82 css css-selectors css3

我正在尝试用一个叫做的类来选择第h1一个.它是有效的,如果它是这个中的第一个元素,但如果它在此之后它将无法工作.divdetail_containerh1divul

<style type="text/css">
.detail_container h1:first-child
{
color:blue;
} 
</style>
</head>
<body>
<div class="detail_container">
    <ul>
    <li></li>
    <li></li>
    </ul>
    <h1>First H1</h1>
    <h1>Second H1</h1>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的印象是我拥有的CSS h1无论在哪里都会选择第一个div.我怎样才能使它工作?

Bol*_*ock 196

h1:first-child选择装置


当且仅当它是h1元素时,选择其父元素的第一个子元素.

所述:first-child容器的这里是ul,这样不能满足h1:first-child.

:first-of-type你的案例有CSS3 :

.detail_container h1:first-of-type
{
    color: blue;
} 
Run Code Online (Sandbox Code Playgroud)

但是由于浏览器兼容性问题和诸如此类的东西,你最好先给出h1一个类,然后定位该类:

.detail_container h1.first
{
    color: blue;
}
Run Code Online (Sandbox Code Playgroud)

  • [兼容性列表](http://www.quirksmode.org/css/contents.html#t34)的`:first-of-type`选择器. (9认同)
  • [较新的兼容性列表](http://www.quirksmode.org/css/selectors/) of `:first-of-type`。旧链接不正确。 (4认同)
  • 我现在明白了,尽管我认为他们在创建标准时应该已经实现了两个版本。 (2认同)

Rob*_*ers 11

:first-childh1 当且仅当它是其父元素的第一个子元素时才选择第一个.在你的例子中,它ul是第一个孩子div.

伪类的名称是有点误导,但它解释清楚漂亮这里的规范.

jQuery的:first选择器为您提供所需的内容.你可以这样做:

$('.detail_container h1:first').css("color", "blue");


Gre*_*ekz 9

对于特定情况,您可以使用:

.detail_container > ul + h1{ 
    color: blue; 
}
Run Code Online (Sandbox Code Playgroud)

但是如果你在很多情况下需要相同的选择器,你应该有一个类,比如BoltClock说.


Fab*_*ice 8

你也可以使用

.detail_container h1:nth-of-type(1)
Run Code Online (Sandbox Code Playgroud)

通过将数字 1 更改为任何其他数字,您可以选择任何其他 h1 项目。