:first-child not working as expected(: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-child为ul,因此不能满足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 anh1element.
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 没有按预期工作
 
				
         
 
            
        - 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 400或500级别的HTTP响应 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
 
						 
						 
						 
						 
						