一场特异性之战!(以及其他技巧)

Avatar of Francisco Dias
Francisco Dias 发布

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200美元免费额度!

以下是来自 HubSpot 的 Francisco Dias 的客座文章。我在今年的 CSS Dev Conf 上看到 Francisco 和 Cris Necochea 以快速有趣的演示形式展示了这一点。 展示与讲述。他欣然同意为一篇博文准备它!

19种覆盖背景色的方法

从几乎最低特异性选择器开始

div {
  background: black;
}

有很多方法可以提升现有特异性,而无需重复相同的技巧。

点击每个步骤,查看间谍如何将其颜色(黑色或白色)强制覆盖在之前的颜色之上。当特异性提升停止时,他们袖子里还有更多技巧!

(间谍形状是通过演示中div上的clip-path创建的,使其更有趣且更像间谍大战。如果您当前使用的浏览器不支持clip-path,您将只会看到白色或黑色方块。)

查看 CodePen 上 Francisco Dias 的作品 间谍大战 (@FranDias)。

这里到底发生了什么?上面演示 CodePen 中的文本包含有关每个步骤的更多信息,但作为快速概述,以下是各个阶段

步骤 1:元素选择器

0, 0, 0, 1

div {
  background: black;
}

步骤 2:两个元素选择器

0, 0, 0, 2

body div {
  background: white;
}

步骤 3:三个元素选择器

0, 0, 0, 3

html body div {
  background: black;
}

步骤 4:类选择器

0, 0, 1, 0

.spy {
  background: white;
}

步骤 5:类 + 元素选择器

0, 0, 1, 1

div.spy {
  background: black;
}

步骤 6:元素 + 类 + 伪类选择器

0, 0, 2, 1

div.spy:only-of-type {
  background: white;
}

步骤 7:堆叠类

0, 0, ∞, 0

.spy.spy.spy.spy.spy.spy.spy.spy.spy {
  background: black;
}

步骤 8:ID 选择器

0, 1, 0, 0

#spy {
  background: white;
}

步骤 9:ID + 属性选择器

0, 1, 1, 0

#spy[class^="s"] {
  background: black;
}

步骤 10:组合以上多种方法…

0, 1, 3, 3

html body div#spy[class="spy"]:first-of-type.spy {
  background: white;
}

步骤 11:内联样式

1, 0, 0, 0

<div class="spy" id="spy" style="background: black;"></div>

步骤 12:!important

有点像每个属性的 [1, 0, 0, 0](可以覆盖内联样式)。

div {
  background: white !important;
}

步骤 13:在内联样式中使用 !important

有点像每个属性的 [∞, 0, 0, 0],任何 CSS 都无法覆盖。

<div class="spy" id="spy" style="background: black !important;"></div>

步骤 14:box-shadow 技巧

某些属性会绘制在其他属性之上。box-shadow 绘制在背景之上。

div {
  box-shadow: inset 0 9001rem 0 white;
}

步骤 15:反转滤镜

div {
  -webkit-filter: invert(1);
          filter: invert(1);
}

步骤 17:再次使用 !important

所有关于特异性的争夺战都可以再次发生,包括使用!important;进行的针对每个属性的争夺,所以让我们在这里结束它。

div:after {
  background: white !important;
}

步骤 18:@keyframes 技巧

!important不可动画化,因此动画可以覆盖它。

@keyframes white {
  to {
    background: black;
  }
}

div:after {
  animation: white 1s linear;
  animation-play-state: paused;
  animation-delay: -1s;
  animation-fill-mode: forwards;
}

步骤 19:内容着色

在所有内容上放置一个巨大的块状字符会再次翻转颜色!

div:after {
  content: "█";
  line-height: 0;
  color: white;
  font-size: 9001px;
}

大屏幕 Chrome 中的演示 GIF