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

时间:2010-12-22 02:30:45

标签: css css3 css-selectors

我正在尝试使用名为h1的类选择div内的第一个detail_container。如果h1是此div中的第一个元素,则可行,但如果它位于此ul之后,则无效。

<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>

我的印象是,我所拥有的CSS会选择第一个h1,无论它在div中的位置。我怎样才能使它发挥作用?

6 个答案:

答案 0 :(得分:184)

h1:first-child选择器意味着

  

选择其父母的第一个孩子   当且仅当它是h1元素。

此处容器的:first-childul,因此无法满足h1:first-child

您的案例中有CSS3的:first-of-type

.detail_container h1:first-of-type
{
    color: blue;
} 

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

.detail_container h1.first
{
    color: blue;
}

答案 1 :(得分:11)

:first-child选择第一个h1 当且仅当它是其父元素的第一个子元素时。在您的示例中,uldiv的第一个孩子。

伪类的名称有些误导,但在规范中非常明确地解释了here

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

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

答案 2 :(得分:8)

对于这种特殊情况,您可以使用:

.detail_container > ul + h1{ 
    color: blue; 
}

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

答案 3 :(得分:4)

您也可以使用

.detail_container h1:nth-of-type(1)

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

答案 4 :(得分:1)

您可以将h1标记包装在另一个div中,然后第一个标记为first-childdiv甚至不需要样式。这只是隔离这些孩子的一种方式。

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

答案 5 :(得分:0)

该元素不能直接从<body>标记继承。 您可以尝试将其放在<dir style="padding-left:0px;"></dir>标签中。

相关问题