我想要知道css提取器的相关语法
- User
我想要知道css提取器的相关语法
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
我想要知道css提取器的相关语法
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
CSS 选择器(Selector)用于从 HTML 文档中定位和提取元素。以下是核心语法分类及示例:
元素选择器
元素名
p { color: blue; } /* 选择所有 <p> 元素 */
类选择器
.class-name
.header { font-size: 20px; } /* 选择 class="header" 的元素 */
ID 选择器
#id-name
#main-title { font-weight: bold; } /* 选择 id="main-title" 的元素 */
通配符选择器
*
* { margin: 0; } /* 选择所有元素 */
后代选择器
A B
div p { color: red; } /* 选择 <div> 内部所有 <p> */
子元素选择器
A > B
ul > li { list-style: none; } /* 选择 <ul> 的直接子元素 <li> */
相邻兄弟选择器
A + B
h1 + p { margin-top: 0; } /* 紧接在 <h1> 后的第一个 <p> */
通用兄弟选择器
A ~ B
h2 ~ p { color: green; } /* <h2> 后面所有同级的 <p> */
存在属性
[attr]
[target] { border: 1px solid; } /* 带有 target 属性的元素 */
精确匹配属性值
[attr="value"]
[type="submit"] { background: blue; } /* type="submit" 的元素 */
包含子字符串
[attr*="value"]
[class*="btn"] { padding: 5px; } /* class 包含 "btn" 的元素 */
开头匹配
[attr^="value"]
a[href^="https"] { color: green; } /* href 以 "https" 开头的链接 */
结尾匹配
[attr$="value"]
a[href$=".pdf"]::after { content: " (PDF)"; } /* 链接到 PDF 文件 */
状态伪类
a:hover { text-decoration: underline; } /* 鼠标悬停 */
input:focus { border-color: blue; } /* 输入框聚焦 */
li:first-child { font-weight: bold; } /* 父元素的首个子元素 */
位置伪类
tr:nth-child(odd) { background: #eee; } /* 奇数行 */
p:nth-of-type(2) { color: red; } /* 同级中第2个 <p> */
p::first-line { font-weight: bold; } /* 段落首行 */
p::before { content: "→ "; } /* 在 <p> 前插入内容 */
p::after { content: " ←"; } /* 在 <p> 后插入内容 */
::selection { background: yellow; } /* 用户选中的文本 */
群组选择器
A, B, C
h1, h2, h3 { font-family: sans-serif; } /* 同时选择多组元素 */
否定伪类
:not(selector)
div:not(.warning) { opacity: 0.8; } /* 排除 class="warning" 的 div */
选择器优先级按权重计算(从高到低):
!important(覆盖所有)style="...")#id).class, [attr], :hover)p, ::before)示例:
#nav .item:hover = 1 ID + 1 类 + 1 伪类 = 权重值 111
/* 选择表格中除第一行外的所有偶数行 */
tr:not(:first-child):nth-child(even) {
background: #f5f5f5;
}
/* 选择所有空段落 */
p:empty {
display: none;
}
/* 选择包含特定文本的元素(需结合JS,CSS不支持文本内容选择) */
/* 但可用属性选择器模拟部分场景 */
[data-text*="error"] {
color: red;
}
掌握这些选择器可精准定位 99% 的页面元素。建议在浏览器开发者工具中实时测试选择器效果(Ctrl+F 输入选择器验证匹配)。