Selector Reference
10 methodsCSS 选择器参考,涵盖类型、类、ID、关系、伪类与属性选择器。
element类型选择器,匹配所有指定标签名的元素。
Returns
匹配文档中所有该标签名的元素并应用样式。
Example
css
div {
display: block;
margin: 0;
}
p {
line-height: 1.6;
}.class类选择器,匹配带有指定 class 属性的元素。
Returns
匹配所有拥有该 class 的元素并应用样式。
Example
css
.card {
padding: 16px;
border-radius: 8px;
}
.button.primary {
background: #007bff;
}#idID 选择器,匹配具有指定 id 的唯一元素。
Returns
匹配文档中具有该 id 的唯一元素并应用样式。
Example
css
#header {
position: sticky;
top: 0;
z-index: 100;
}A B后代选择器,匹配 A 元素内部的所有 B 元素(任意层级)。
Returns
选中作为 A 后代的 B 元素并应用样式。
Example
css
article p {
color: #333;
}
nav ul li {
list-style: none;
}A > B子代选择器,仅匹配 A 元素的直接子元素 B。
Returns
选中 A 的直接子级 B 元素,深层嵌套不匹配。
Example
css
ul > li {
padding-left: 8px;
}
div > p:first-child {
font-weight: bold;
}A + B相邻兄弟选择器,匹配紧接在 A 之后的同级 B 元素。
Returns
选中紧随 A 之后的第一个 B 兄弟元素。
Example
css
h1 + p {
margin-top: 0;
}
label + input {
margin-left: 4px;
}A ~ B通用兄弟选择器,匹配 A 之后的所有同级 B 元素。
Returns
选中 A 之后的所有 B 兄弟元素(不必相邻)。
Example
css
h1 ~ p {
color: #555;
}
input ~ .hint {
font-size: 0.85em;
}:hover伪类,匹配用户鼠标悬停时的元素状态。
Returns
在鼠标悬停时应用样式,鼠标移出后恢复。
Example
css
a:hover {
color: #0056b3;
text-decoration: underline;
}
.button:hover {
opacity: 0.9;
}:nth-child(n)结构伪类,匹配父元素中第 n 个子元素,支持公式与关键字。
Returns
按位置公式选中符合条件的子元素并应用样式。
Example
css
li:nth-child(odd) {
background: #f9f9f9;
}
li:nth-child(3n+1) {
color: red;
}
p:nth-child(2) {
font-weight: bold;
}[attr=value]属性选择器,匹配属 性值等于/包含/以特定模式开头的元素。
Returns
按属性值条件筛选元素并应用样式。
Example
css
input[type="text"] {
border: 1px solid #ccc;
}
a[href^="https"] {
color: green;
}
a[class~="icon"] {
padding-left: 20px;
}