微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – :first-child不能按预期工作

我试图选择第一个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>

我的印象是,我已经选择了第一个h1,无论它在这个div。如何使它工作?

解决方法

h1:第一子选择器表示

Select the first child of its parent
if and only if it’s an h1 element.

这里的容器的第一个孩子是ul,因此不能满足h1:first-child。

有CSS3的:第一类型为您的情况:

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

但是与浏览器兼容性的困扰和什么,你最好给第一个h1一个类,然后针对该类:

.detail_container h1.first
{
    color: blue;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。