Skip to content

选择器

选择器汇总

标志选择器类型作用写法示例
*通配选择器选中所有标签,一般用于清除样式。* { color: orange; font-size: 40px; }
元素选择器为某些元素统一设置样式h1 { color: orange; font-size: 40px; } p { color: blue; font-size: 60px; }
.类选择器选中所有特定类名(class值)的元素.speak { color: red; } .answer { color: blue; }
#ID 选择器选中特定id值的那个元素(唯一的)#earthy { color: red; font-size: 60px; }
A B后代选择器选中指定元素中,符合要求的后代元素ul li { color: red; } ul li a { color: orange; } .subject li { color: blue; } .subject li.front-end { color: blue; }
A > B子代选择器选中指定元素中,符合要求的子元素div > a { color: red; } .persons > a { color: red; }
A + B相邻兄弟选择器选中指定元素后,符合条件的相邻兄弟元素div + p { color: red; }
A ~ B通用兄弟选择器选中指定元素后,符合条件的所有兄弟元素div ~ p { color: red; }

属性选择器

标志选择器类型作用写法示例
[attr]属性选择器选中具有某个属性的元素div[title] { color: red; }
[attr=value]属性选择器选中包含某个属性,且属性值等于指定值的元素div[title="atguigu"] { color: red; }
[attr^=value]属性选择器选中包含某个属性,且属性值以指定的值开头的元素div[title^="a"] { color: red; }
[attr$=value]属性选择器选中包含某个属性,且属性值以指定的值结尾的元素div[title$="u"] { color: red; }
[attr*=value]属性选择器选中包含某个属性,属性值包含指定值的元素div[title*="g"] { color: red; }

伪类选择器

标志选择器类型作用写法示例
:link伪类选择器选中超链接未被访问的状态a:link { color: blue; }
:visited伪类选择器选中超链接访问过的状态a:visited { color: purple; }
:hover伪类选择器选中鼠标悬停的状态a:hover { color: red; }
:active伪类选择器选中按下鼠标不松开的状态a:active { color: yellow; }
:focus伪类选择器选中获取焦点的状态input:focus { border: 2px solid blue; }
:first-child伪类选择器选中所有兄弟元素中的第一个li:first-child { color: green; }
:last-child伪类选择器选中所有兄弟元素中的最后一个li:last-child { color: green; }
:nth-child(n)伪类选择器选中所有兄弟元素中的第 n 个li:nth-child(2) { color: green; }
:first-of-type伪类选择器选中所有同类型兄弟元素中的第一个p:first-of-type { color: green; }
:last-of-type伪类选择器选中所有同类型兄弟元素中的最后一个p:last-of-type { color: green; }
:nth-of-type(n)伪类选择器选中所有同类型兄弟元素中的第 n 个p:nth-of-type(2) { color: green; }
plain
顺序为:link > visited > hover > active