Skip to content

选择器

CSS3 新增选择器

css
a[class^="column"] {
  background: red;
}
a[href$="doc"] {
  background: green;
}
a[title*="box"] {
  background: blue;
}

^ 开头
$ 结尾
* 包含

:root

根选择器

根元素始终是<html>

:not

否定选择器

css
input:not([type="submit"]) {
  border: 1px solid red;
}

除 submit 按钮之外的 input 都添加 border

:empty

选择 没有任何内容的元素

空格 也算内容!
空格 就不算 :empty

:target

目标选择器

表示一个唯一的元素(目标元素),其 id 与当前 URL 片段匹配。

https://developer.mozilla.org/zh-CN/docs/Web/CSS/:target

看 MDN 的 demo

:first-child / :last-child

兄弟元素中的第一个元素

:first-child / :last-child 要求比较纯,建议不用

html
<div>
  <p>此文本已选中!</p>
  <p>此文本未选中。</p>
</div>

<div>
  <div>此文本未被选中:它不是一个 p。</div>
  <p>此文本未被选中。</p>
</div>
css
p:first-child {
  color: lime;
  background-color: black;
  padding: 5px;
}

此文本已选中!

此文本未选中。

此文本未被选中:它不是一个 p。

此文本未被选中。

last-child

css
li:last-child {
  border: 2px solid orange;
}

是 li 不是 ul

:nth-child(n) / :nth-last-child(n)

https://developer.mozilla.org/zh-CN/docs/Web/CSS/:nth-child

n 从 1 开始
n 还支持 odd 和 even 关键字
n 还支持高级语法

根据 元素 在 父元素 的中的索引来选择元素。

换言之,:nth-child() 选择器根据父元素内的所有兄弟元素的位置来选择子元素。

:first-of-type / :last-of-type

作用于 兄弟元素,并且 type。

html
<div class="wrapper">
  <p>p 1</p>
  <p>p 2</p>
  <div>div 1</div>
  <div>div 2</div>
  <p>p 3</p>
  <div>div 3</div>
</div>
css
.wrapper > p:first-child,
.wrapper > div:first-child {
  background: #1e8ae8;
}

div:first-child 不会生效

p:first-child 会生效

css
.wrapper > p:first-of-type,
.wrapper > div:first-of-type {
  border: 1px solid orange;
}

p 和 div 的 :first-of-type 都会生效

p 1

p 2

div 1
div 2

p 3

div 3

对比 first-child ,他的要求没有么高,就算 div 不是第一个元素,也可以。

nth-of-type(n) / nth-last-of-type(n)

作用于 兄弟元素

html
<div class="wrapper">
  <div>Div Div Div Div Div</div>
  <p>P P P P P</p>
  <div>Div Div Div Div Div</div>
  <p>P P P P P</p>
</div>
css
.wrapper > div:nth-of-type(2) {
  background-color: cadetblue;
}

.wrapper > p:nth-of-type(1) {
  background-color: rgb(190, 87, 234);
}
Div Div Div Div Div

P P P P P

Div Div Div Div Div

P P P P P

支持 odd、even、2n、2n+1 这样的参数

:only-child

父元素中只有一个子元素,而且只有唯一的一个子元素。

vue
<template>
  <div class="post">
    <p>我是一个段落</p>
    <p>我是一个段落</p>
  </div>
  <div class="post">
    <p>我是一个段落</p>
  </div>
</template>

<style scoped>
.post p {
  background: green;
  color: #fff;
  padding: 10px;
}
.post p:only-child {
  background: orange;
}
</style>

我是一个段落

我是一个段落

我是一个段落

:only-of-type

万军丛中取唯一

我是一个段落

我是一个段落

我是一个Div元素

我是一个段落

我是一个段落

vue
<template>
  <div class="wrapper">
    <p>我是一个段落</p>
    <p>我是一个段落</p>
    <div>我是一个Div元素</div>
    <p>我是一个段落</p>
    <p>我是一个段落</p>
  </div>
</template>

<script setup lang="ts"></script>

<style scoped>
div:only-of-type {
  background-color: cornflowerblue;
}
</style>