CSS选择器详解

118 阅读4分钟

什么是CSS选择器

CSS选择器是CSS规则的第一部分,它用于选择需要应用样式的HTML元素。通过不同的选择器,我们可以精准地定位到页面中的元素并为其添加样式。

基本选择器

元素选择器

通过HTML元素名称选择元素,是最基本的选择器。

h1 { color: red; }
p { font-size: 16px; }

类选择器

通过元素的class属性选择元素,以 . 开头。

.container { width: 1200px; margin: 0 auto; }
.text-center { text-align: center; }

ID选择器

通过元素的id属性选择元素,以 # 开头,具有唯一性。

#header { height: 80px; background: #333; }
#logo { width: 150px; height: 40px; }

通用选择器

选择页面中所有元素,以 * 表示。

* { margin: 0; padding: 0; box-sizing: border-box; }

组合选择器

后代选择器

选择某个元素的所有后代元素,使用空格分隔。

.container p { line-height: 1.5; }
ul li { list-style: none; }

子元素选择器

选择某个元素的直接子元素,使用 > 表示。

.container > p { color: #333; }
.nav > ul { display: flex; }

相邻兄弟选择器

选择紧接在某个元素后的兄弟元素,两者具有相同的父元素,使用 + 表示。

h1 + p { margin-top: 10px; }
.active + li { background: #f5f5f5; }

通用兄弟选择器

选择某个元素后面的所有兄弟元素,两者具有相同的父元素,使用 ~ 表示。

h1 ~ p { color: #666; }

属性选择器

根据元素的属性或属性值来选择元素。

基本属性选择器

input[type] { border: 1px solid #ccc; }
a[href] { text-decoration: none; }

属性值选择器

input[type="text"] { width: 200px; }
a[href="https://example.com"] { color: blue; }

部分属性值选择器

a[class~="button"] { padding: 8px 16px; }
input[name^="user"] { background: #fff; }
img[src$=".jpg"] { border-radius: 4px; }
div[class*="content"] { margin: 20px 0; }

伪类选择器

用于选择处于特定状态的元素,以 : 开头。

状态伪类

a:link { color: blue; }
a:visited { color: purple; }
a:hover { color: red; }
a:active { color: yellow; }
input:focus { outline: 2px solid blue; }

结构伪类

/* 选择第一个子元素 */
ul li:first-child { font-weight: bold; }
/* 选择最后一个子元素 */
ul li:last-child { margin-bottom: 0; }
/* 选择第n个子元素 */
.container p:nth-child(3) { color: #f00; }
/* 选择偶数位置的子元素 */
tr:nth-child(even) { background: #f9f9f9; }
/* 选择奇数位置的子元素 */
tr:nth-child(odd) { background: #fff; }
/* 选择唯一的子元素 */
div:only-child { margin: 0 auto; }

否定伪类

选择不匹配指定选择器的元素

p:not(.intro) { line-height: 1.6; }
input:not([type="submit"]) { margin-right: 10px; }

伪元素选择器

用于选择元素的特定部分,以 :: 开头。

/* 选择元素的第一个字母 */
p::first-letter { font-size: 2em; }
/* 选择元素的第一行 */
p::first-line { color: #333; }
/* 在元素内容前插入内容 */
.container::before { content: ""; display: block; height: 20px; }
/* 在元素内容后插入内容 */
.container::after { content: ""; display: block; height: 20px; }
/* 选择用户选中的内容 */
::selection { background: yellow; }

选择器优先级

当多个选择器应用于同一个元素时,优先级决定哪个样式生效:

  1. !important声明(最高优先级)
  2. 内联样式
  3. ID选择器
  4. 类选择器、伪类选择器、属性选择器
  5. 元素选择器、伪元素选择器
  6. 通用选择器(最低优先级)

优先级可以通过计算 specificity 值来确定,具体规则为:每个选择器类型分配不同的权重,ID选择器计100,类选择器/伪类/属性选择器计10,元素选择器/伪元素选择器计1,然后相加比较总和。

选择器最佳实践

  1. 保持选择器简洁,避免过度嵌套
  2. 优先使用类选择器,减少ID选择器的使用
  3. 合理使用组合选择器,提高选择效率
  4. 避免使用 !important,通过优化选择器优先级解决样式冲突
  5. 使用有意义的类名,提高代码可读性和可维护性 通过灵活运用各种CSS选择器,我们可以更精确、更高效地为网页元素应用样式,创建出美观且易于维护的CSS代码。