:第一个孩子没有按预期工作 [英] :first-child not working as expected

查看:114
本文介绍了:第一个孩子没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 div 中的第一个 h1 > detail_container 。如果 h1 div 中的第一个元素,但如果它在 ul 它不会工作。

I'm trying to select the first h1 inside a div with a class called detail_container. It works if h1 is the first element within this div, but if it comes after this ul it won't work.

<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 中的何处。

I was under the impression that the CSS I have will select the first h1 no matter where it is in this div. How can I make it work?

推荐答案

h1:first-child 选择器方法


选择其父项的第一个子项

当且仅当它是 h1 元素。

:first-child 这里的容器是 ul ,因此不能满足 h1:first-child

The :first-child of the container here is the ul, and as such cannot satisfy h1:first-child.

对于您的情况,有CSS3的:first-of-type

There is CSS3's :first-of-type for your case:

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

但是对于浏览器兼容性的困扰和什么, h1 一个类,然后定位该类:

But with browser compatibility woes and whatnot, you're better off giving the first h1 a class, then targeting that class:

.detail_container h1.first
{
    color: blue;
}

这篇关于:第一个孩子没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆