选择器进阶
子串选择器
css
/* 匹配 href 以 "https" 开头的链接 */
a[href^="https"] {
color: green;
}
/* 匹配 href 包含 "example" 的链接 */
a[href*="example"] {
text-decoration: underline;
}
/* 匹配 href 以 ".pdf" 结尾的链接 */
a[href$=".pdf"]::after {
content: "📄";
}
伪类
- 状态伪类
css
/* 未访问链接 */
a:link { color: blue; }
/* 已访问链接 */
a:visited { color: purple; }
/* 鼠标悬停 */
button:hover { background: #eee; }
/* 输入框获取焦点时 */
input:focus { outline: 2px solid orange; }
- 结构伪类
css
/* 第一个子元素 */
ul li:first-child { font-weight: bold; }
/* 最后一个子元素 */
ul li:last-child { border-bottom: none; }
/* 第3个元素 */
ul li:nth-child(3) { color: red; }
/* 奇数行 */
tr:nth-child(odd) { background: #f5f5f5; }
伪元素
- ::before / ::after
css
/* 在元素前插入内容 */
h1::before {
content: "🌟";
margin-right: 10px;
}
/* 在元素后插入内容 */
.price::after {
content: "元";
color: #999;
}
- ::selection
css
/* 文本选中样式 */
::selection {
background: yellow;
color: black;
}
其他选择器
- 群组选择器
css
/* 同时选择 h1-h3 */
h1, h2, h3 {
font-family: Arial;
}
- 否定伪类
css
/* 排除 .disabled 的按钮 */
button:not(.disabled) {
cursor: pointer;
}