一、伪类
1、锚点
关于锚点< a>有五个伪类,:link、:hover、:active、:focus、:visited
a:link{background-color:pink;}/品红,未访问/
a:visited{color:orange;}/字体颜色为橙色,已被访问/
a:focus{background-color:lightgrey;}/浅灰,拥有焦点/
a:hover{background-color:lightblue;}/浅蓝,鼠标悬停/
a:active{background-color:lightgreen;}/浅绿,正被点击/
2、UI元素伪类(主要用于form元素)
- UI元素伪类包括:enabled、:disabled、:checked三个,主要针对于HTML中的form元素
:enabled : 可用状态
:disabled : 不可用状态
:checked : 选中状态
//css
input:enabled{
background-color: lightblue
}
input:disabled{
background-color:pink;
}
//html
<form>
可以写字:<input type="text"/><br/>
不可以写字:<input type="text" disabled="disabled" /><br/>
默认选中:<input type="checkbox" checked="checked"/><br/>
未设置选中:<input type="radio" />
</form>
3、结构伪类
//以下情况都是E为父元素,F为子元素
E F:nth-child(n) 选择父元素的第n个子元素
E F:nth-last-child(n) 选择父元素的倒数第n个子元素
E F:first-child 父元素的第一个子元素,与E F:nth-child(1)等同
E F:last-child 父元素的最后一个子元素,与E F:nth-last-child(1)等同
E F:only-child 当前元素的父元素,有且只有它本身一个子元素(DOM节点)时,修改其样式
- 第一行的n可以是整数( 从1开始),也可以是公式,也可以是关键字(even、odd):even代表偶数位置的子元素;odd:代表奇数位置的子元素
//html
<ul>
<li><div>第一个DIV</div></li>
<li><div>第二个DIV</div></li>
<li><div>第三个DIV</div></li>
<li><div>第四个DIV</div></li>
<li><div>第五个DIV</div></li>
<li><div>第六个DIV</div></li>
</ul>
//css
ul li:nth-child(odd){
color: red;}
ul li:nth-last-child(3){
color: green;}
ul li:first-child{
color: blue;}
ul li:last-child{
color: yellow;}
div:only-child{
background-color:lightgrey;}
二、伪元素
伪元素顾名思义伪装成元素,但不是元素,这与生成内容相关。生成内容主要指由浏览器创建的内容,而不是由标志或内容来表示。生成内容主要由:before和:after伪元素来实现,当然伪元素还包括:first-line,:first-letter和::selection
1、:first-letter:指定一个元素第一个字母的样式
- 注意:只能与块级元素关联
//html
<div class="letter">测试首字母下层,测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层</div>
测试首字母下层,测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层测试首字母下层
//css
.letter{
width: 200px;
border: 1px solid black;
}
.letter::first-letter{
font-size: 30px;
float: left;
}
2、first-line:设置元素中第一行文本的样式
- 注意:只能与块级元素关联
//html
<p class="firstLine">hello world hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world </p>
hello world hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world
//css
.firstLine::first-line {
width: 200px;
text-transform: uppercase;//变成大写
background: yellow;
}
::selection:匹配被用户选择的部分
- 注意:只支持颜色和背景颜色两个样式
//html
<p>123456</p>
//css
p::selection {
color:blue;
background-color: #ccc;
}