CSS(层叠样式表)是一种用于描述HTML或XML(包括SVG、MathML等各种XML方言)文档样式的样式表语言。CSS提供了多种选择器,用于选择和样式化文档中的特定元素。
:first-child
:选择其父元素的第一个子元素。:first-of-type
:选择其父元素中第一个特定类型的子元素。:nth-child(n)
:选择其父元素的第n个子元素。:nth-of-type(n)
:选择其父元素中第n个特定类型的子元素。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS选择第一个元素</title>
<style>
/* 选择第一个子元素 */
.container > :first-child {
color: red;
}
/* 选择第一个特定类型的子元素 */
.container > p:first-of-type {
font-weight: bold;
}
/* 选择第n个子元素 */
.container > :nth-child(3) {
background-color: yellow;
}
/* 选择第n个特定类型的子元素 */
.container > p:nth-of-type(2) {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<p>这是第一个段落。</p>
<p>这是第二个段落。</p>
<div>这是一个div。</div>
<p>这是第三个段落。</p>
</div>
</body>
</html>
通过这些选择器,你可以灵活地选择和样式化HTML文档中的第一个元素,从而实现更丰富的页面效果。
领取专属 10元无门槛券
手把手带您无忧上云