Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一行 CSS 为网页添加暗黑模式支持 #76

Open
sisterAn opened this issue Aug 10, 2020 · 1 comment
Open

一行 CSS 为网页添加暗黑模式支持 #76

sisterAn opened this issue Aug 10, 2020 · 1 comment

Comments

@sisterAn
Copy link
Owner

本文将介绍一种简单易懂的方法实现网站支持暗黑模式

话不多说,我们开始吧! 👾

以以下新闻应用程序为例:

现在仅需增加以下一行魔法 CSS:

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

添加后页面展示效果:

哇偶! 瞬间转换成暗黑模式有没有✌️

解析

filter CSS 属性将模糊或颜色偏移等图形效果应用于元素。滤镜通常用于调整图像,背景和边框的渲染。(参考:MDN Web文档

对于暗黑模式,将使用两个 filterinverthue-rotate

invert:反转配色。黑色变为白色,白色变为黑色,所有颜色都是如此

hue-rotate:帮助我们处理所有其他非黑色和白色的颜色。 将色相旋转180度,我们确保应用程序的颜色主题不会改变,而只是减弱其颜色。

这个方法的唯一缺点是,它还会反转应用程序中的所有图像。

因此,我们将对所有图像添加相同的规则,以逆转效果。

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

我们还将向HTML元素添加一个 transition ,以确保过渡不会过于花哨!

html {
    transition: color 300ms, background-color 300ms;
}

实现结果👇:

@touryung
Copy link

请问大佬,背景图片可以设置吗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants