伪类与伪元素选择器
链接伪类
:link
:表示作为超链接,并指向一个为访问的地址的所有锚
:visited
:表示作为超链接,并指向一个已访问的地址的所有锚
a{text-decoration: none;}
a:link{color: deeppink;}
#test :link{background: pink;}
:target
:代表一个特殊元素,它的id是URL的片段标识符
:target实例-选项卡,html结构如下
<body>
<a href="#div1">div1</a>
<a href="#div2">div2</a>
<a href="#div3">div3</a>
<div id="div1">
div1
</div>
<div id="div2">
div2
</div>
<div id="div3">
div3
</div>
</body>
css结构如下
*{
margin: 0;
padding: 0;
}
a{
text-decoration: none;
color: deeppink;
}
div{
width: 200px;
height: 200px;
background: pink;
display: none;
text-align: center;
font: 50px/200px "微软雅黑";
}
:target{
display: block;
}
注意:
:link
,:visited
,:target
是作用与链接元素的
动态伪类
:hover
:表示悬浮到元素上
:active
:表示匹配被用户激活的元素(点击按住)
由于a标签的:link和:visited可以覆盖了所有的a标签的状态,所以当:link,:visited,:hover,:active同时出现在a标签身上时,:link和:visited不能放在最后
注意::hover和:active基本可以作用于所有的元素
表单相关伪类
:enabled
:匹配可编辑的表单
:disable
:匹配被禁用的表单
:checked
:匹配被选中的表单
:focus
:匹配获焦的表单
实例如下
input:enabled{
background: deeppink;
}
input:disabled{
background: blue;
}
input:checked{
width: 200px;
height: 200px;
}
input:focus{
background: darkcyan;
}
html结构如下
<input type="text" />
<input type="text" disabled="disabled" />
<input type="checkbox" />
小例子-自定义单选按钮
<label>
<input type="radio" name="mj" />
<span></span>
</label>
<label>
<input type="radio" name="mj" />
<span></span>
</label>
<label>
<input type="radio" name="mj" />
<span></span>
</label>
css代码如下
*{
margin: 0;
padding: 0;
}
label{
position: relative;
float: left;
width: 100px;
height: 100px;
border: 2px solid;
overflow: hidden;
border-radius: 50%;
}
label > span{
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
}
input{
position: absolute;
left: -50px;
top: -50px;
}
input:checked + span{
background: pink;
}
结构性伪类选择器
:nth-child(index)系列
- :first-child
- :last-child
- nth-last-child(index):表示从后面开始计数
- only-child(相当于:first-child:last-child或者:noth-child(1):nth-last-child(1))
:nth-child(index)实例
/*找到#warp底下的所有li子元素,并且选中第一个子元素,并且这个子元素必须是li*/
#wrap li:nth-child(1){
color: deeppink;
}
注意:1.index的值从1开始计数;2.index可以为变量n(只能是n);3.index可以为even或者odd
:nth-of-type系列
- :first-of-type
- last-of-type
- nth-last-type(index):表示从后面开始计数
- only-of-type
#wrap li:nth-of-type(1){
color: deeppink;
}
注意:nth-child(index)和nth-of-type(index)的区别:前者找某某下的第一个适配元素,后者找某某下的出现第一次的适配元素。
nth-child和nth-of-type的区别(坑)
html结构如下
<div id="warp">
<div class="inner">div</div>
<span class="inner">span</span>
<p class="inner">p</p>
<h1 class="inner">h1</h1>
<h2 class="inner">h2</h2>
</div>
使用nth-child如下,这个没什么问题,选中的是#warp下的class为.inner的第一个元素div
#warp .inner:nth-child(1){
color: deeppink;
}
使用nth-of-type如下,选中的却是所有元素,这是因为nth-of-type是以元素为中心
#warp .inner:nth-of-type(1){
color: deeppink;
}
- not
div > a:not(:last-of-type){
border-right: 1px solid red;
}
- enpty(内容必须是空的,有空格都不行)