CSS-选择器(2)-伪类和伪元素
::表示法是在
CSS 3中引入的,::符号是用来区分伪类和伪元素的。支持CSS3的浏览器同时也都支持CSS2中引入的表示法:
。 IE8仅支持:
。
1. 伪元素
- after: 在匹配元素的最后插入一个子元素
- before: 在匹配元素的最前面插入一个子元素
- placeholder: 控制placeholder的样式
- selection: 控制文本选中的样式,比如鼠标选中一段文本的样式(只支持少许颜色背景色轮廓等属性)
- slotted: 插槽样式(未求证)
css代码
.t::before {
content: '前置插入元素';
color: red;
}
.t::after {
content: '后置插入元素';
color: blue;
}
input::placeholder {
color: red;
}
.sec::selection {
color: green;
}
html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>测试</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<p class="t">测试伪类</p>
<br>
<input placeholder="测试提示语" type="text">
<br>
<section class="sec">选中文本样式</section>
</body>
</html>
2. 伪类
- link 未激活的链接元素,比如a标签
- visited 已激活的链接元素,比如a标签
- hover 用户鼠标悬停的元素
- active 激活的元素,按住状态
- checked 选中的元素
- defined 已定义的或自定义的元素
- disabled 禁用状态的元素
- empty 无子元素的元素
- enabled 启用状态的元素
- first-child 第一个子元素
- first-of-type 类型第一的子元素
- last-child 最后一个子元素
- last-of-type 类型最后的子元素
- focus 聚焦状态的元素
- host host() SHADOW DOM元素的样式
- indeterminate 不确定状态的元素,比如input=checkbox且属性indeterminate为true
- in-range out-of-range 存在最大范围和最小范围区间属性(比如input的min和max)的元素样式
- invalid valid 无效格式和有效格式的匹配元素,常用于input=email等
- lang 匹配lang属性对应的元素
- not(selectors) 反选伪类,
- nth-child(an+b) 根据表达式(n自增1)的值匹配指定的子元素
- nth-of-type(an+b) 根据表达式的值(n自增1)匹配指定类型的子元素
- nth-last-child(an+b) 与nth-child从前往后匹配相反,它从后往前匹配
- nth-last-of-type(an+b) 与nth-last-of-type从前往后匹配相反,它从后往前匹配
- only-child 匹配无兄弟元素的元素
- only-of-type 匹配无同类型兄弟元素的元素
- placeholder-shown 匹配placeholder属性的元素,搭配text-overflow属性
- read-only 匹配不可编辑状态的元素,比如input和设置了contenteditable属性的节点
- required inpu可选外观
- root 这个 CSS 伪类匹配文档树的根元素。对于 HTML 来说,:root 表示 元素,除了优先级更高之外,与 html 选择器相同
- target 代表一个唯一的页面元素(目标元素),其id 与当前URL片段匹配
- scope 它表示作为选择器要匹配的参考点的元素