The*_*Man 82 css css-selectors css3
我正在尝试用一个叫做的类来选择第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>
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)
对于特定情况,您可以使用:
.detail_container > ul + h1{
color: blue;
}
Run Code Online (Sandbox Code Playgroud)
但是如果你在很多情况下需要相同的选择器,你应该有一个类,比如BoltClock说.
你也可以使用
.detail_container h1:nth-of-type(1)
Run Code Online (Sandbox Code Playgroud)
通过将数字 1 更改为任何其他数字,您可以选择任何其他 h1 项目。