这是一个全面的 css 选择器备忘单,涵盖了您可能需要的所有基本和高级选择器:
1. 基本选择器
- 通用选择器 (*):针对所有元素。
* {
margin: 0;
}
- 类型选择器(元素选择器):针对给定类型的元素。
p {
color: blue;
}
- 类选择器(.classname):针对具有特定类的元素。
.container {
width: 100%;
}
- id 选择器 (#idname):定位具有特定 id 的元素。
#header {
background-color: grey;
}
2. 属性选择器
- [attribute]:定位具有指定属性的元素。
[type="text"] {
border: 1px solid black;
}
- [attribute=value]:定位具有确切属性值的元素。
[type="checkbox"] {
display: inline-block;
}
- [attribute^=value]:定位属性以指定值开头的元素。
[href^="https"] {
color: green;
}
- [attribute$=value]:定位属性以指定值结尾的元素。
[href$=".pdf"] {
color: red;
}
- [attribute*=value]:定位属性包含指定值的元素。
[class*="button"] {
font-weight: bold;
}
3. 组合选择器
- 后代选择器(空格):定位另一个元素内的元素。
div p {
color: blue;
}
- 子选择器 (>):针对父元素的直接子元素。
ul > li {
list-style-type: none;
}
- 相邻同级选择器 (+):定位紧邻指定元素之前的第一个元素。
h2 + p {
margin-top: 0;
}
- 通用兄弟选择器 (~):针对指定元素之前的所有元素(不一定是直接)。
h2 ~ p {
color: green;
}
4. 伪类
- :hover:当光标悬停时定位元素。
a:hover {
text-decoration: underline;
}
- :focus:定位具有焦点的元素。
input:focus {
border-color: blue;
}
- :nth-child(n):定位其父级的第 n 个子级。
li:nth-child(2) {
color: red;
}
- :nth-of-type(n):定位其类型的第 n 个子级。
p:nth-of-type(3) {
font-size: 1.2em;
}
- :first-child / :last-child:定位其父级的第一个或最后一个子级。
p:first-child {
font-weight: bold;
}
- :not(selector):排除与选择器匹配的元素。
p:not(.highlight) {
color: grey;
}
5. 伪元素
- ::before / ::after:在元素内容之前或之后插入内容。
p::before {
content: "note: ";
font-weight: bold;
}
- ::first-letter:定位元素的第一个字母。
p::first-letter {
font-size: 2em;
}
- ::first-line:定位元素内文本的第一行。
p::first-line {
font-style: italic;
}
6. 分组选择器
- 分组选择器(,):将相同的样式应用于多个选择器。
h1, h2, h3 {
color: blue;
}
7. 特殊组合器
- 空选择器 (:empty):定位没有子元素或文本的元素。
div:empty {
display: none;
}
- 启用/禁用选择器(:enabled / :disabled):针对启用或禁用的表单元素。
input:enabled {
background-color: white;
}
input:disabled {
background-color: lightgrey;
}
- 选中选择器 (:checked):针对选中的复选框或单选按钮。
input:checked {
border-color: green;
}
8. 高级选择器
- :nth-child(odd) / :nth-child(even):针对奇数或偶数子级。
tr:nth-child(even) {
background-color: lightgrey;
}
- :nth-last-child(n):定位倒数第 n 个子级。
li:nth-last-child(1) {
color: red;
}
- :only-child:目标元素是其父元素的唯一子元素。
div:only-child {
border: 1px solid red;
}
- :root:定位文档 (html) 的根元素。
:root {
--main-color: blue;
}
9. 属性存在和值选择器
- [属性]:定位具有给定属性的元素。
[required] {
border: 2px solid red;
}
- [attribute^=value]:定位属性以特定值开头的元素。
[href^="http"] {
text-decoration: underline;
}
- [attribute$=value]:定位属性以特定值结尾的元素。
[href$=".pdf"] {
color: red;
}
- [attribute*=value]:定位属性包含特定值的元素。
[class*="icon"] {
background-color: yellow;
}
10. 其他选择器
- :lang(语言):匹配特定语言的元素。
p:lang(en) {
color: blue;
}
- :target:定位 id 与 url 片段匹配的元素。
#section:target {
background-color: yellow;
}
结论
本备忘单涵盖了大多数 css 选择器,从基础到高级。以创造性的方式组合它们可以让您有效地定位特定元素并精确控制网页的外观。