伪类选择器分为结构性、子元素、 UI、动态和其它伪类选择器
备注:为了更好的区分伪类和伪元素,书写上CSS做了区分。例如,伪类 :first-child;伪元素 ::after
大部分伪类选择器如下图所示
:root返回<html>
在下面的示例中:
div > p:only-child{
color:red; //不变红
}
div > p:only-of-type{
color:red; //变红
}
<div>
<p>test1</p>
<span>test2</span>
</div>
ul > li:nth-child(2){
color:red; //选择该元素所有子元素的第二个子元素
}
ul > li:nth-last-child(2){
color:red; //选择该元素所有子元素的倒数第二个子元素
}
ul > li:nth-of-type(2){
color:red; //选择该元素所有该类型子元素的第二个子元素
}
ul > li:nth-last-of-type(2){
color:red; //选择该元素所有该类型子元素的倒数第二个子元素
}
:target{
color:red; //定位到锚点,选择此元素
}
//锚点的定位:
首先在HTML元素中定义一个ID属性值,例如<p id="test">asd</p>
然后在浏览器地址栏,在URL最后加上#test,便可以定位到该锚点了。
锚点的使用:
可以用来将一篇很长的文章分段,
eg.<a href="#02">跳转到</a>
<p id="02">……</p>
其实锚点只需name就可以可,加id是为了让它兼容性更好
所谓UI选择器:就是指定的样式只有当元素处于某种状态下时,才起作用,在默认状态下不起作用!
浏览器兼容性:
E:hover 支持firefox、safari、Opera、ie8、chrome ------------
E:active 支持firefox、safari、Opera、chrome 不支持ie8
E:focus 支持firefox、safari、Opera、ie8、chrome -------------
E:enabled 支持firefox、safari、Opera、chrome 不支持ie8
E:disabled 支持firefox、safari、Opera、chrome 不支持ie8
E:read-only 支持firefox、Opera 不支持ie8、safari、chrome
E:read-write 支持firefox、Opera 不支持ie8、safari、chrome
E:checked 支持firefox、safari、Opera、chrome 不支持ie8
E::selection 支持firefox、safari、Opera、chrome 不支持ie8
E:default 只支持firefox ------------
E:indeterminate 只支持chrome ------------
E:invalid 支持firefox、safari、Opera、chrome 不支持ie8
E:valid 支持firefox、safari、Opera、chrome 不支持ie8
E:required 支持firefox、safari、Opera、chrome 不支持ie8
E:optional 支持firefox、safari、Opera、chrome 不支持ie8
E:in-range 支持firefox、safari、Opera、chrome 不支持ie8
E:out-of-rang 支持firefox、safari、Opera、chrome 不支持ie8
下面就其使用做详细的说明;
1、选择器E:hover、E:active和E:focus
1)、E:hover选择器被用来指定当鼠标指针移动到元素上时元素所使用的样式
使用方法:
<元素>:hover{
CSS样式
}
我们可以在“<元素>”中添加元素的type属性。
例:
input[type="text"]:hover{
CSS样式
}
2)、E:active选择器被用来指定元素被激活时使用的样式
3)、E:focus选择器被用来指定元素获得光标聚焦点使用的样式,主要是在文本框控件获得聚焦点并进行文字输入时使用。
例如:
2、E:enabled伪类选择器与E:disabled伪类选择器
1)、E:enabled选择器被用来指定当元素处于可用状态时的样式。
2)、E:disabled选择器被用来指定当元素处于不可用状态时的样式。
例如:
3、E:read-only伪类选择器与E:read-write伪类选择器
1)、E:read-only选择器被用来指定当元素处于只读状态时的样式。
2)、E:read-write选择器被用来指定当元素处于非只读状态时的样式。
4、伪类选择器E:checked、E:default和indeterminate
1)、E:cehcked伪类选择器用来指定当表单中的radio单选框或者是checkbox复选框处于选取状态时的样式。
2)、E:default选择器用来指定当页面打开时默认处于选取状态的单选框或复选框的控件的样式。
3)、E:indeterminate选择器用来指定当页面打开时,一组单选框中没有任何一个单选框被设定为选中状态时,整组单选框的样式。
默认的选择项
5、伪类选择器E::selection
1)、E:selection伪类选择器用来指定当元素处于选中状态时的样式。
例如
6、E:invalid伪类选择器与E:valid伪类选择器
1)、E:invalid伪类选择器用来指定,当元素内容不能通过HTML5通过使用的元素的诸如requirde等属性所指定的检查或元素内容不符合元素规定的格式时的样式。
2)、E:valid伪类选择器用来指定,当元素内容能通过HTML5通过使用的元素的诸如requirde等属性所指定的检查或元素内容符合元素规定的格式时的样式。
例如
7、E:required伪类选择器与E:optional伪类选择器
1)、E:required伪类选择器用来指定允许使用required属性,而且已经指定了required属性的input元素、select元素以及textarea元素的样式。
2)、E:optional伪类选择器用来指定允许使用required属性,而且未指定了required属性的input元素、select元素以及textarea元素的样式。
8、E:in-range伪类选择器与E:out-of-range伪类选择器
1)、E:in-range伪类选择器用来指定当元素的有效值被限定在一段范围之内,且实际的输入值在该范围之内时的样式。
2)、E:out-of-range伪类选择器用来指定当元素的有效值被限定在一段范围之内,但实际输入值在超过时使用的样式。
例如