蘑菇小姐会开花

有关css选择器

最近好忙,赶需求赶需求,赶完一个又一个。css好渣,对现如今还在使用IE6的用户真是深恶痛绝,每次改兼容性就是小半天过去了。吐槽了这么久,来说一说前段时间调样式的时候犯的错吧,有关css选择器。

:first-child 选择器

:first-child 选择器用于选取属于其父元素的首个子元素的指定选择器。

1
2
3
4
5
6
p:first-child {
font-weight: bold; //将作为某元素第一个子元素的所有p设置为粗体
}
li:first-child {
text-transform: uppercase; //将某个元素第一个子元素的所有li元素变成大写
}

最常见的误解是:认为p:first-child这样的选择器会选择p元素的第一个子元素
此外,对于较早版本的IE浏览器,<!DOCTYPE>必须声明,:first-child才会生效。

举个栗子:
匹配作为任何元素的第一个子元素的p元素

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<style type="text/css">
p:first-child {
color: red;
}
</style>
</head>
<body>
<p>some text</p>
<p>some text</p>
</body>
</html>

匹配所有p元素中的第一个元素

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<style type="text/css">
p > i:first-child {
font-weight:bold;
}
</style>
</head>
<body>
<p>some <i>text</i>. some <i>text</i>.</p>
<p>some <i>text</i>. some <i>text</i>.</p>
</body>
</html>

匹配所有作为第一个子元素的p元素中所有的i元素

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<style type="text/css">
p:first-child i {
color:blue;
}
</style>
</head>
<body>
<p>some <i>text</i>. some <i>text</i>.</p>
<p>some <i>text</i>. some <i>text</i>.</p>
</body>
</html>

坚持原创技术分享,您的支持将鼓励我继续创作!