iCSS icon indicating copy to clipboard operation
iCSS copied to clipboard

CSS 在夜间模式/深色模式中的使用与探索

Open chokcoco opened this issue 5 years ago • 5 comments

本文未完成....


法一:使用 filter: invert

主要借助 invert 这个滤镜实现,定义一个 .dark-mode-invert 挂载在全局根元素 <html>上:

filter: invert(): 反转输入图像。值定义转换的比例。100%的价值是完全反转。值为0%则图像无变化。值在0%和100%之间,则是效果的线性乘子。 若值未设置,值默认是0。

图片不能使用 filter: invert 处理,需要再 invert(100%) 转变回来。

.dark-mode-invert {
    filter: invert(100%);
}

.dark-mode-invert img {
    filter: invert(100%);
}

尝试使用掘金作为例子试了下:

转换前: image

转换后: image

缺点:

  1. 需要对图片额外处理,如果图片是以 background 嵌入的方式则工作量更大
  2. 转换后的非黑白色不好控制,且效果一般

法二:使用混合模式 mix-blend-mode: difference

chokcoco avatar Nov 29 '19 13:11 chokcoco

转换后有内味儿了

TrumanGu avatar Nov 30 '19 05:11 TrumanGu

@TrumanGu 还在探索中 :joy:

chokcoco avatar Nov 30 '19 05:11 chokcoco

可以通过 Media Query 查询 prefers-color-scheme 属性来检测用户系统的主题。

hexuan-aurora avatar Mar 27 '20 09:03 hexuan-aurora

可以用css atrribute+css变量来做,类似这样: body {--primary-color: white} body[theme="dark"] {--primary-color: black} .button: {background: var(--primary-color)} 给body加theme="dark"就ok了

dk-plus avatar Mar 04 '21 10:03 dk-plus

可以用css atrribute+css变量来做,类似这样: body {--primary-color: white} body[theme="dark"] {--primary-color: black} .button: {background: var(--primary-color)} 给body加theme="dark"就ok了

这个在低版本一点android的webview就存在很大问题了,不支持attribute的属性,直接挂球

Harhao avatar Feb 22 '24 09:02 Harhao