7个让你眼前一亮的CSS选择器!

1. :is()

mdn: CSS 伪类函数以选择器列表作为参数,并选择该列表中任意一个选择器可以选择的元素。这对于以更紧凑的形式编写大型选择器非常有用

备注: 最初该选择器被命名为 :matches()以及 :any()),但在 CSSWG issue #3258 中被重命名为 :is()

选中header main footer中的所有段落并绑定hover状态:

header p:hover,
main p:hover,
footer p:hover {
color: red;
}

使用 :is() 可以简化成以下写法:

:is(header, main, footer) p:hover {
color: red;
}

2. :where()

mdn: CSS 伪类函数接受选择器列表作为它的参数,将会选择所有能被该选择器列表中任何一条规则选中的元素

用法:

选中header main footer中的所有段落并绑定hover状态:

header p:hover,
main p:hover,
footer p:hover {
color: red;
}

使用 :where() 可以简化成以下写法:

:where(header, main, footer) p:hover {
color: red;
}

是不是感觉:is():where()的用法一模一样?

:is():where()的用法和作用是很相似的,唯一不同的在于,:where() 的优先级总是为 0,但是 :is() 的优先级是由它的选择器列表中优先级最高的选择器决定的

3. :not()

:not() CSS伪类用来匹配不符合一组选择器的元素。由于它的作用是防止特定的元素被选中,它也被称为反选伪类negation pseudo-class)**

用法:

<p>我是一个段落。</p>
<p class="fancy">我非常非常喜欢!</p>
<div>我不是一个段落。</div>
<h2>
<span class="foo">foo 在 h2 里面</span>
<span class="bar">bar 在 h2 里面</span>
</h2>
.fancy {
text-shadow: 2px 2px 3px gold;
}

/* 类名不是 `.fancy` 的 <p> 元素*/
p:not(.fancy) {
color: green;
}

/* 非 <p> 元素 */
body :not(p) {
text-decoration: underline;
}

/* 既不是 <div> 也不是 <span> 的元素 */
body :not(div):not(span) {
font-weight: bold;
}

/* 不是 <div> 或 `.fancy` 的元素*/
body :not(div, .fancy) {
text-decoration: overline underline;
}

/* <h2> 元素中不是有 `.foo` 类名的 <span> 元素 */
h2 :not(span.foo) {
color: red;
}

4. :only-child

:only-child CSS 伪类表示没有任何兄弟元素的元素。这与 :first-child、:last-child:nth-child(1)、:nth-last-child(1) 相同,但前者具有更小的权重性。

用法

<ol>
<li>今天天气晴朗,是个敲代码的好日子</li>
</ol>

<ol>
<li>今天天气晴朗,是个敲代码的好日子</li>
<li>但是写了很多bug.</li>
<li>这很让我头疼.</li>
</ol>
li:only-child {
color: fuchsia;
}

b:only-child {
text-decoration: underline;
}
运行效果
运行效果

5. :root

:root 这个 CSS 伪类匹配文档树的根元素。对于 HTML 来说,:root 表示<html>元素,除了优先级更高之外,与 html 选择器相同。

用法:

你可以使用:root选择器定义一个变量--main-bg-color,并在任意一个选择器中使用var来调用--main-bg-color

:root {
--main-bg-color: lightgreen;
}
.main {
background: var(--main-bg-color);
}

6. :empty

:empty CSS伪类用于选择不包含任何子元素的元素。子元素可以是元素节点或文本(包括空格)。但是注释、处理指令和 CSS content不会影响元素是否被认定为空。

用法:

<p>下面的节点没有内容</p>
<div></div>
<p>下面的节点有空的标签</p>
<div>
<p>123456</p>
</div>

<p>下面的节点有注释</p>
<div><!-- 这里是注释 --></div>

<p>下面的节点有空格</p>
<div> </div>

<p>下面的节点有空的标签</p>
<div>
<p></p>
</div>
div:empty {
outline: 2px solid deeppink;
height: 1em;
width: 100px;
}
运行效果
运行效果

7. :invalid

:invalid 是 CSS伪类选择器,用来选择任何未通过验证的<form><fieldset><input>或其他表单元素。

<form>
<label for="form-name">姓名</label>
<input type="text" name="name" id="form-name" required />
<button type="submit">提交</button>
</form>
form:invalid > button {
opacity: 0.3;
pointer-events: none;
}

填入内容前/后的效果对比:

运行效果
运行效果

本文由 mdnice 多平台发布

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半截短袖_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值