1 :first-child
p:first-child {
background-color:yellow;
}
阅读理解:<p>
元素的背景设为黄色 + 第一个子元素的背景设为黄色 = 父元素的第一个子元素是<p>
时,该子元素背景设为黄色
举个栗子:
<!DOCTYPE html>
<html>
<head>
<style>
p:first-child {
background-color: yellow;
}
</style>
</head>
<body>
<p>这个段落是其父元素(body)的首个子元素, 且为p</p>
<p>这个段落是其父元素的第二个子元素。</p>
<div>
<p>这个段落是其父元素(div)的首个子元素,且为p</p>
<p>这个段落不是其父元素的第二个子元素。</p>
</div>
</body>
</html>
2 :first-of-type
p:first-of-type {
background:#ff0000;
}
阅读理解:<p>
元素的背景设为黄色 + 第一个<p>
类型元素的背景设为黄色 = 父元素的子元素中,第一个<p>
元素背景设为黄色,不一定要是第一个子元素噢
举个例子:
<!DOCTYPE html>
<html>
<head>
<style>
p:first-of-type {
background-color: yellow;
}
</style>
</head>
<body>
<h5>这个段落是其父元素(body)的第一个子元素</h5>
<p>这个段落是其父元素(body)的第一个p子元素</p>
<p>这个段落是其父元素的第二个p子元素。</p>
<div>
<h5>这个段落是其父元素(div)的第一个子元素</h5>
<p>这个段落是其父元素(div)的第一个p子元素</p>
<p>这个段落不是其父元素的第二个p子元素。</p>
</div>
</body>
</html>
参考、实践地址:
https://www.w3school.com.cn/cssref/selector_first-child.asp
https://www.w3school.com.cn/cssref/selector_first-of-type.asp