1.属性选择器+伪类元素
选择器 | 说明 |
---|---|
E[attr^=“xxx”] | 选择元素E,其中E元素的attr属性是以xxx开头的任何字符 |
E[attr$=“xxx”] | 选择元素E,其中E元素的attr属性是以xxx结尾的任何字符 |
E[attr*=“xxx”] | 选择元素E,其中E元素的attr属性是包含xxx的任何字符 |
若要在如下代码的两个a标签前面加上图标,则需要选中这两个a标签。
<body>
<ul>
<li><a href="test.doc" download>下载doc文件</a></li>
<li><a href="test.pdf" download>下载pdf文件</a></li>
</ul>
</body>
<style>
ul{
list-style-type: none;
}
/* a[href$="doc"]::after{
content: url('./image/wps.png');
} */
a[href$="doc"]::after{
content: '';
display: inline-block;
width: 20px;
height: 20px;
background-image: url('./image/wps.png');
background-size: cover;
}
a[href$="pdf"]::before{
content: '';
display: inline-block;
width: 20px;
height: 20px;
background-image: url('./image/pdf.png');
background-size: cover;
}
</style>
实现效果如下:
注意:
其实直接 content:url() 就可以插入伪类元素,添加图片,但是这样添加的图片不能设置宽高大小,因此利用背景图片这个属性,来实现可设置图标的宽高。
2.子元素伪类选择器
子元素伪类选择器特别适合操作列表的不同样式!
在CSS3中,子元素伪类选择器有两大类:
- (1):first-child、:last-child、:nth-child(n)、:only-child(实际开发中,掌握第一种就好)
- (2):first-of-type、:last-of-type、:nth-of-type(n)、:only-of-type(不用特别关注)
第一类:
选择器 | 说明 |
---|---|
E:first-child | 选择父元素下的第一个子元素(该子元素类型为E,以下类同) |
E:last-child | 选择父元素下的最后一个子元素 |
E:nth-child(n) | 选择父元素下的第n个子元素或奇偶元素,n取值有3种:数字、odd和even,其中n从1开始 |
E:only-child | 选择父元素下唯一的子元素,该父元素只有一个子元素 |
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<style>
ul li{
width: 200px;
height: 20px;
}
/* 错误写法:使用子伪类选择器时,冒号前面的元素是其本身,而不是其父类元素 */
/* ul:nth-child(1){
background-color: chocolate;
} */
li:nth-child(odd){
background-color: chocolate;
}
li:nth-child(even){
background-color: cadetblue;
}
</style>
实现效果如下:
3.UI伪类选择器
指的是针对“元素的状态”来选择元素的一种伪类选择器。UI,全称“User Interface”,也就是用户界面。
元素的状态包括:可用、不可用、选中、未选中、获取焦点、失去焦点等。
在CSS3中,UI伪类选择器主要包括以下5类。
- (1):focus
- (2)::selection
- (3):checked
- (4):enabled和:disabled
- (5):read-write和:read-only
下面举例说明前两中选择器的使用:
<body>
<p><label for="user">账号:</label><input id="user" type="text"/></p>
<p><label for="pwd">密码:</label><input id="pwd" type="password"/></p>
<button>click me</button>
<p>默认情况下,使用鼠标来选取页面的文本内容时,该文本内容都是以“蓝色背景、白色字体”来显示的,在CSS3中,我们可以使用::selection选择器来定义页面中被选中文本的样式。</p>
</body>
<style>
input:focus{
outline-color: coral;
}
button:focus{
color:coral;
}
p::selection{
color:rgb(218, 176, 162);
background-color: cadetblue;
}
/* 兼容火狐浏览器 */
p::-moz-selection{
color:rgb(218, 176, 162);
background-color: cadetblue;
}
</style>
实现效果如下:
注意:在实际开发中,我们很少单独对某个元素定义选中样式,一般都是统一为整个页面的选中文本定义样式,此时 ::selection 前面不需要添加任何元素即可。
4.其他伪类选择器
除了前几节中介绍的伪类选择器之外,CSS3还为我们提供了其他几种伪类选择器。
- (1):root (HTML页面的根元素,与html等同效果)
- (2):empty (“不包含任何子元素和内容”的元素,也就是选择一个空元素。)
- (3):target (所谓的target元素,指的是id被当成页面的锚点链接来使用的元素。)
- (4):not() (重点掌握)
<body>
<ul>
<li class="first">hahahahaha</li>
<li>hahahahaha</li>
<li>hahahahaha</li>
<li>hahahahaha</li>
</ul>
</body>
<style>
li:not(.first){
color: red;
}
</style>
实现效果如下:
如果没有借助:not()选择器,想要实现上面这种效果是非常麻烦的一件事,冗余代码也非常多。