25

一行代码实现黑暗模式

 3 years ago
source link: https://www.infoq.cn/article/3CQX2B1iZIScmGQoeYE5
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

其实黑暗模式可以用一行代码来实现。我们看看具体是怎么做到的。

以这个模板为例

M7neIjn.png!mobile

现在添加神奇的 CSS

复制代码

html[theme='dark-mode']{
filter:invert(1)hue-rotate(180deg);
}

就这些!你搞定了✌

auENFjm.png!mobile

黑暗模式完成,但其实有点不合适。

说明

现在我们试着看看幕后发生了什么。

filter 这个 CSS 属性将模糊或颜色偏移等图形效果应用于某个元素。这些滤镜通常用于调整图像、背景和边框的渲染。

对于这种黑暗模式,我们将使用两个滤镜,分别是 invert 和 hue-rotate

invert滤镜用来反转应用程序的配色方案。也就是说黑色会变成白色,白色变成黑色,所有颜色以此类推。invert() 函数作为 filter 属性的值将取 0 到 1 之间的数字,或 0%到 100%的百分比。

hue- rotate滤镜可以帮助我们处理所有非黑色和白色的颜色。它能将色相旋转 180 度,让我们可以确保应用程序的配色方案不变,而只是减弱其颜色。

aumAzqn.png!mobile

使用这种方法的唯一陷阱是,它还将反转应用程序中的所有图像、图片和视频。因此,我们将向所有图像添加相同的规则以反转效果。

复制代码

html[theme='dark-mode']img,
picture,
video{
filter:invert(1)hue-rotate(180deg);
}

并且我们要添加一个类,以反转特定标签内的效果。

复制代码

.invert{
filter:invert(1)hue-rotate(180deg);
}

结果 ‍

eINjmyR.png!mobile

这样我们就成功实现了黑暗模式。

BBulma 和 Bulma 的模板是基于 Flexbox 的免费开源 CSS 框架。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK