h2:first-child与h2:first-of-type选择器未按预期生效问题求助
问题分析与解决方案
嘿,我来帮你搞清楚为什么h2:first-of-type会选中所有<h2>元素!
核心原因:first-of-type是基于父元素上下文的选择器
你可能误以为h2:first-of-type会选中整个页面的第一个<h2>,但实际上它的作用是:选中某个父元素下的第一个<h2>类型元素。
看你的HTML结构:
<article>里的第一个<h2>是<article>的第一个<h2>,会被选中;- 每个
<section>(包括<article>里的三个section、<aside>里的section)里的<h2>都是各自父元素<section>的第一个<h2>(同时也是第一个子元素),所以这些<h2>都会被h2:first-of-type匹配到; - 甚至
<aside>里的<h2>也符合它父元素<section>的first-of-type条件。
这就导致所有<h2>都被这个选择器命中,样式被覆盖成#444。
解决方案:指定目标父容器
如果你只想选中**<article>下的第一个直接子元素<h2>**(也就是“A little bit about me”那个标题),需要把选择器限定到特定父容器,比如:
/* 只选中article下的第一个直接子h2 */ article > h2:first-of-type { color: #444; }
如果你的需求是选中整个页面中的第一个<h2>,可以用更上层的父容器来限定:
/* 选中body下出现的第一个h2 */ body h2:first-of-type { color: #444; }
关于first-child的补充
h2:first-child的逻辑类似:它选中的是父元素的第一个子元素,且这个子元素是<h2>。你的每个<section>里的<h2>都是父元素的第一个子元素,所以同样会被全部命中,和first-of-type效果一致。
修改后的完整CSS示例
这里是调整后的CSS,只让<article>的第一个直接子<h2>变成#444:
* { box-sizing: border-box; font-family: sans-serif; text-align: justify; color: #000; } .row { display: flex; gap: 40px; } .options { font-size: 18px; display: flex; gap: 20px; } .description { display: flex; gap: 20px; align-items: center; } h1, h2 { color: #1098ad; } /* 修改这里,限定父容器 */ article > h2:first-of-type { color: #444; } article { flex: 1; margin-bottom: 0; } aside h2 { text-align: center; } aside { margin-top: 20px; background-color: #f4f4f4; border-top: 5px solid #83989b; border-bottom: 5px solid #83989b; align-self: flex-start; flex: 0 0 230px; }
这样就能达到你想要的“仅第一个h2生效”的效果啦!
内容的提问来源于stack exchange,提问作者leviakc
相关产品推荐
相关产品推荐

