first-of-type 伪类用于选择父元素下第一个指定类型的子元素,如 div p:first-of-type 仅选中第一个 p 元素并应用样式;2. first-of-type 与 first-child 的区别在于前者按元素类型选择首个匹配项,后者选择父元素的第一个子元素,无论类型;3. first-of-type 可与类、id 或属性选择器组合使用,如 .container p:first-of-type 实现精确样式控制,但 p.special:first-of-type 若非首个同类型元素则不生效;4. 实际应用包括文章首段排版、列表首项样式、表单首个输入框样式及响应式设计优化,提升网页美观性与用户体验。

HTML设置首个子类型样式,主要通过
first-of-type
解决方案:
first-of-type
立即学习“前端免费学习笔记(深入)”;
例如,假设你有以下 HTML 结构:
<div> <p>This is the first paragraph.</p> <p>This is the second paragraph.</p> <span>This is a span.</span> <p>This is the third paragraph.</p> </div>
如果你想只给第一个
<p>
first-of-type
div p:first-of-type {
color: blue;
font-weight: bold;
}在这个例子中,只有 "This is the first paragraph." 这段文字会变成蓝色加粗。其他的
<p>
<span>
<p>
first-of-type
first-of-type
first-child
first-of-type
first-child
first-child
first-of-type
考虑以下 HTML 结构:
<div> <span>This is a span.</span> <p>This is the first paragraph.</p> <p>This is the second paragraph.</p> </div>
如果使用
first-child
div :first-child {
color: red;
}那么 "This is a span." 这段文字会变成红色,因为它是
<div>
如果使用
first-of-type
div span:first-of-type {
color: green;
}
div p:first-of-type {
color: blue;
}那么 "This is a span." 会变成绿色,"This is the first paragraph." 会变成蓝色。
first-of-type
first-of-type
first-of-type
假设你有以下 HTML 结构:
<div class="container"> <p>First paragraph in container.</p> <p class="special">Second paragraph in container.</p> <p>Third paragraph in container.</p> </div> <div> <p>First paragraph in another div.</p> </div>
你可以这样使用:
.container p:first-of-type {
font-style: italic;
}
p.special:first-of-type {
text-decoration: underline; /* 这里不会生效,因为 .special 不是父元素的 first-of-type */
}在这个例子中,只有 "First paragraph in container." 这段文字会变成斜体。
.special
<p>
<p>
text-decoration
text-decoration
<p>
.special
first-of-type
first-of-type
article p:first-of-type {
font-size: 1.2em;
color: #333;
}<ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
ul li:first-of-type {
margin-top: 0;
background-color: #f0f0f0;
}<form> <input type="text" placeholder="First Name"> <input type="text" placeholder="Last Name"> </form>
form input:first-of-type {
border: 1px solid blue;
}这些都是
first-of-type
以上就是HTML如何设置首个子类型样式?first-of-type伪类的用法是什么?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号