:first-child 没有按预期工作

:first-child not working as expected(:first-child 没有按预期工作)

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

问题描述

我正在尝试使用名为 detail_container 的类选择 div 内的第一个 h1.如果 h1 是这个 div 中的第一个元素,它可以工作,但如果它出现在这个 ul 之后,它将不起作用.

<style type="text/css">.detail_container h1:first-child{颜色:蓝色;}</风格></头><身体><div class="detail_container"><ul><li></li><li></li></ul><h1>第一个 H1</h1><h1>第二个H1</h1></div></身体></html>

我的印象是我拥有的 CSS 将选择第一个 h1,无论它在这个 div 中的什么位置.我怎样才能让它发挥作用?

解决方案

h1:first-child选择器的意思

<块引用>

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

这里容器的:first-childul,因此不能满足h1:first-child.p>

您的情况有 CSS3 的 :first-of-type:

.detail_container h1:first-of-type{颜色:蓝色;}

但是由于浏览器兼容性问题等等,你最好给第一个 h1 一个类,然后定位那个类:

.detail_container h1.first{颜色:蓝色;}

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>

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?

解决方案

The h1:first-child selector means

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

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

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

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

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

这篇关于:first-child 没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为::first-child 没有按预期工作

基础教程推荐