属性选择器
- 元素的属性,我们都知道是什么。例如下面代码中
type
和value
就是input
元素的属性。属性选择器,顾名思义,就是通过属性来选择元素的一种方式。
<input type="text" value="abc"/>
属性选择器 说明
E[attr^="abc"] 选取了元素E,其中E元素定义了属性att,att属性值是以abc开头的任何字符串。
E[attr$="abc"] 选取了元素E,其中E元素定义了属性att,att属性值是以abc结尾的任何字符串。
E[attr*="abc"] 选取了元素E,其中E元素定义了属性att,att属性值任意位置是包含了abc的任何字符串。
结构伪类选择器
- 结构伪类选择器,是针对HTML层次“结构”的伪类选择器。例如我们想要某一个父元素下面的第
n
个子元素
结构伪类选择器.png
div p:first-child{
/*选择父元素的第一个子元素*/
background: red;
}
div p:last-child{
/*选择父元素的最后一个子元素*/
background: green;
}
div p:nth-child(5){
/*选择父元素下的第n个元素或奇偶元素,n的值为“数字 | odd | even”*/
background: yellow;
}
div p:nth-child(odd){
/*选择父元素下的第n个元素或奇偶元素,n的值为“数字 | odd | even”*/
background: black;
}
div p:only-child{
/*选择父元素中唯一的子元素(该父元素只有一个子元素)*/
background: pink;
}
结构伪类选择器(2)
:first-of-type 选择同元素类型的第1个同级兄弟元素
:last-of-type 选择同元素类型的最后1个同级兄弟元素
:nth-of-type(n) 匹配同元素类型的第n个同级兄弟元素,n的值为“数字 | odd | even”
:only-of-type 匹配父元素中特定类型的唯一子元素(该父元素可以有多个子元素)
- 以上解释,大家看着比较难懂,需要结合一下实例才能真正理解。
<div>
<h1></h1>
<p></p>
<span></span>
<span></span>
</div>
1):first-child
h1:first-child:选择的是h1元素,因为h1元素是div的第1个子元素。
p:first-child:选择不到任何元素,因为p并不是div的第1个子元素,而是div的第2个子元素。
span:first-child:选择不到任何元素,因为span并不是div的第1个子元素,而是div的第3个子元素;
2):first-of-type
h1:first-of-type:选择的是h1元素,因为h1元素是div中所有h1元素中的第1个h1元素,事实上也只有一个为h1的子元素;
p:first-of-type:选择的是p元素,因为p元素是div中所有p元素中的第1个p元素,事实上也只有一个为p的子元素;
span:irst-of-type:选择的是id="first"的span元素,因为在div元素中有2个span元素,我们选择的是两个之中的第1个
总结:
:first-child
是选择父元素下的第1个子元素(不区分元素类型),而:first-of-type
是选择父元素下某个元素类型的第1个子元素(区分元素类型)。
:last-child
和:last-of-type
、nth-child(n)
和:nth-of-type(n)
同样也可以这样去理解
:root选择器
- 在
CSS3
中,:root
选择器用于选择文档的根元素。根元素指的是位于文档树中最顶层结构的元素。在HTML
中,根元素永远是HTML
<style type="text/css">
:root {
background-color: silver;
}
body {
background-color: red;
}
</style>
<body>
<h1>abcde</h1>
</body>
- 这里使用
:root
选择器指定整个网页的背景色为灰色,将网页中body
元素的背景色设为红色。
:root{background-color:silver;}
上述代码等价于:
html{background-color:silver;}
:not()选择器
- 在
CSS3
中,:not()
选择器中主要用于选取某个元素之外的所有元素。这是very very
实用的一个选择器
<style type="text/css">
ul li:not(.first) {
color: red;
}
</style>
<ul>
<li class="first">123</li>
<li>123</li>
<li>123</li>
<li>123</li>
</ul>
:empty选择器
- 在
CSS3
中,:empty
选择器用于选择一个不包含任何子元素或内容的元素。也就是选择一个内容为空白的元素。
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS3 :empty选择器</title>
<style type="text/css">
table,
tr,
td {
border: 1px solid silver;
}
td {
width: 60px;
height: 60px;
line-height: 60px;
text-align: center;
background-color: #FFA722;
}
td:empty {
background-color: red;
}
</style>
</head>
<body>
<table>
<tr>
<td>2</td>
<td>4</td>
<td>8</td>
</tr>
<tr>
<td>16</td>
<td>32</td>
<td>64</td>
</tr>
<tr>
<td>128</td>
<td>256</td>
<td></td>
</tr>
</table>
</body>
</html>
-
在浏览器预览效果如下:
:emptyxuan'ze'qi
-
在网页表格中,对于内容为空的单元格往往设置不同的颜色,使得用户体验更好。网页版的
HTML5
游戏2048
也用到了:empty
选择器这个技术。
:target选择器
-
:target
选择器用于选取页面中的某个target
元素。那什么是target
元素呢?target
元素,说白了就是该元素的id
被当做页面的超链接来使用。 - 当点击锚点链接时,相应的
target
元素下的h3
标签字体颜色就会变为红色。 -
:target
选择器一般都是结合锚点链接来使用,更好地给读者进行导航效果,这也是对用户体验非常好的一个做法。
网友评论