跳到主要内容

选择器

选择器

基本概念

  • 选择器: HTML 元素匹配模式;
  • 作用: 定位 CSS 规则的应用目标;

css 选择器的读取顺序

  • 从右向左;

元素选择器

  • 直接匹配 html 元素;
a {
color: red;
}

通用选择器

  • 匹配所有 html 元素;
* {
color: green;
}

选择器列表

  • 一个 CSS 规则匹配多个选择器;
h1,
.special {
color: blue;
}

class 选择器

  • .class: 匹配指定 class 的所有元素;
  • element.class: 匹配指定元素和 class;
  • .class1.class2: 匹配同时具有多个 class 的元素;
/* All elements with class="spacious" */
.spacious {
margin: 2em;
}

/* All <li> elements with class="spacious" */
li.spacious {
margin: 2em;
}

/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
margin: 2em;
}

id 选择器

#demo {
border: red 2px solid;
}

结合元素选择器

li#demo {
border: red 2px solid;
}

属性选择器

语法格式

  • [attr]: 匹配具有 attr 属性的元素;
  • [attr=value]: 匹配 attr 属性值等于 value 的元素;
  • [attr~=value]: 匹配 attr 属性值列表包含 value 的元素;
  • [attr|=value]: 匹配 attr 属性值等于 value 或以 value- 开头的元素;
  • [attr^=value]: 匹配 attr 属性值以 value 开头的元素;
  • [attr$=value]: 匹配 attr 属性值以 value 结尾的元素;
  • [attr*=value]: 匹配 attr 属性值包含 value 子串的元素;
  • [attr operator value i]: 大小写不敏感匹配;
/* Links with "example" anywhere in the URL */
a[href*="example"] {
background-color: silver;
}

/* Links with "insensitive" anywhere in the URL,
regardless of capitalization */
a[href*="insensitive" i] {
color: cyan;
}
同时使用多个属性选择器
/* Links that start with "https" and end in ".org" */
a[href^="https"][href$=".org"] {
color: green;
}

选择器操作符

后代选择器

  • 目标元素: li;
  • 匹配条件: ul.my-things 的后代元素;
ul.my-things li {
margin: 2em;
}

子代选择器

  • 目标元素: li;
  • 匹配条件: ul.my-things 的直接子元素;
ul.my-things > li {
margin: 2em;
}

相邻兄弟选择器

  • 目标元素: p;
  • 匹配条件: 与 img 直接相邻的后续同级元素;
img + p {
font-weight: bold;
}

通用兄弟选择器

  • 目标元素: p;
  • 匹配条件: 位于 img 后方的同级元素;
img ~ p {
color: red;
}

伪类

基本概念

  • 伪类: 匹配元素的特定状态;
  • 使用方式类似 class 选择器;
button:hover {
color: blue;
}

伪类列表

伪元素

伪元素

  • 伪元素: 匹配元素的特定部分;
  • 使用方式类似虚拟元素;
p::first-line {
color: blue;
text-transform: uppercase;
}

伪元素列表