:first-child伪类通过匹配父元素的第一个直接子元素来应用样式,不关心元素类型,适用于列表、导航等场景;而:first-of-type则选择特定类型的首个子元素,更适用于类型优先的场景。两者核心区别在于前者基于位置,后者基于元素类型,实际使用中需注意DOM结构变化、特异性冲突及动态内容插入的影响。<p>
<p>在HTML中要设置首个子元素的样式,最直接、最常用的方法就是利用CSS的:first-child
:first-child
<div>
<h1>
<p>
<ul>
:first-child
<h1>
<div>
<ul> <li>这是第一项 <li>这是第二项 <li>这是第三项 <p>列表下面的一个段落。<p>立即学习“前端免费学习笔记(深入)”;
.my-list-container ul li:first-child {
color: red;
font-weight: bold;
}li:first-child
<ul>
<li>
:first-child
<ul>
<h2>
li:first-child
<li>
<ul>
<h2>
:first-child
:first-child
:first-child
<p>
<p>这是一篇文章的第一个段落,我想让它有点特别。 <p>这是第二个段落,它就保持常规样式。 <p>第三个段落也一样。
article p:first-child {
text-indent: 2em;
font-size: 1.1em;
color: #333;
}nav ul li {
margin-left: 15px; /* 所有li都有左边距 */
}
nav ul li:first-child {
margin-left: 0; /* 第一个li的左边距清零 */
}:first-child
:first-of-type
:first-child
:first-of-type
<h2>文章标题 <p>这是第一段文字。 <p>这是第二段文字。 这是一个span元素。 <p>这是第三段文字。
p:first-child
p
div.content
<h2>
p:first-child
<p>
p:first-of-type
div.content
<p>
<p>
p:first-of-type
<p>
h2:first-child
h2
div.content
h2:first-child
<h2>
h2:first-of-type
div.content
<h2>
<h2>
h2:first-of-type
<h2>
<h2>
:first-child
:first-of-type
<p>
<h2>
:first-child
:first-of-type
<p>
:first-of-type
:first-child
:first-child
:first-child
:first-child
<div class="card-list">
<div class="card">卡片1</div>
<div class="card">卡片2</div>
</div>.card:first-child { border-top: none; }<div class="card-list">
<h3>卡片列表标题</h3>
<div class="card">卡片1</div>
<div class="card">卡片2</div>
</div>.card:first-child
<div class="card">卡片1</div>
.card-list
<h3>
:first-of-type
h3 + .card
:first-child
:first-child
:first-child
:first-child
:first-child
:first-child
以上就是HTML如何设置首个子元素样式?first-child伪类的用法是什么?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号