通过使用伪类选择器可以有条件的为某元素的指定子元素设置样式。
1 :first-child 用来选中元素的第一个子元素
:last-child 用来选择元素的最后一个子元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
/*
为div元素的第一个p子元素设置样式,
注意:第一个子元素必须是p标签,否则不起作用
* */
div > p:first-child{
background-color: greenyellow;
}
/*为div的最后一个p子元素设置样式,
注意:div的最后一个子元素必须是p标签
* */
/*div > p:last-child{
background-color: greenyellow;
}*/
</style>
</head>
<body>
<h1>戴望舒</h1>
<div>
<p>丁香一样的颜色</p>
<p>丁香一样的芬芳</p>
<p>丁香一样的忧愁</p>
</div>
</body>
</html>
浏览器中显示为:
2、:nth-child 可以选中任意位置的子元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
/*
为div中第二个p元素设置样式
注意:div中第二个子元素必须是p标签
:nth-child 可以选中任意位置的子元素
even 表示偶数位置的子元素
odd 表示奇数位置的子元素
* */
div > p:nth-child(2){
background-color: greenyellow;
}
</style>
</head>
<body>
<h1>戴望舒</h1>
<div>
<p>丁香一样的颜色</p>
<p>丁香一样的芬芳</p>
<p>丁香一样的忧愁</p>
</div>
</body>
</html>
浏览器中显示为:
另外,:first-of-type 、:last-of-type 和 :nth-of-type用法类似,只不过child,是在所有的子元素中排列,而type,是在当前类型的子元素中排列。