我在黑暗中看到你眼中的月光_你好黑暗,我的老朋友

我在黑暗中看到你眼中的月光

(Originally published on https://web.dev/prefers-color-scheme/.)

(最初發布于https://web.dev/prefers-color-scheme/ 。)

介紹 (Introduction)

📚 I have done a lot of background research on the history and theory of dark mode, if you are only interested in working with dark mode, feel free to skip the introduction.

📚我已經對暗模式的歷史和理論進行了很多背景研究,如果您只對使用暗模式感興趣,請隨時跳過介紹 。

黑暗模式之前的黑暗模式 (Dark mode before Dark Mode)

Image for post
Source)來源 )

We have gone full circle with dark mode. In the dawn of personal computing, dark mode wasn’t a matter of choice, but a matter of fact: Monochrome CRT computer monitors worked by firing electron beams on a phosphorescent screen and the phosphor used in early CRTs was green. Because text was displayed in green and the rest of the screen was black, these models were often referred to as green screens.

我們在黑暗模式下走了一個完整的圈。 在個人計算的曙光中,暗模式不是選擇問題,而是事實:單色CRT計算機顯示器通過在磷光屏上發射電子束來工作,而早期CRT中使用的磷光是綠色的。 由于文本顯示為綠色,而屏幕的其余部分為黑色,因此這些型號通常稱為綠色屏幕 。

Image for post
Source)來源 )

The subsequently introduced Color CRTs displayed multiple colors through the use of red, green, and blue phosphors. They created white by activating all three phosphors simultaneously. With the advent of more sophisticated WYSIWYG desktop publishing, the idea of making the virtual document resemble a physical sheet of paper became popular.

隨后推出的彩色CRT通過使用紅色,綠色和藍色磷光體顯示多種顏色。 他們通過同時激活所有三種熒光粉來產生白色。 隨著更先進的所見即所得桌面發布的出現,使虛擬文檔類似于物理紙的想法變得流行。

Image for post
Source)源 )

This is where dark-on-white as a design trend started, and this trend was carried over to the early document-based web. The first ever browser, WorldWideWeb (remember,CSS wasn’t even invented yet), displayed webpages this way. Fun fact: the second ever browser, Line Mode Browser — a terminal-based browser — was green on dark. These days, web pages and web apps are typically designed with dark text on a light background, a baseline assumption that is also hard-coded in user agent stylesheets, including Chrome’s.

這是從深色開始作為設計趨勢的起點,并且這種趨勢被延續到了早期的基于文檔的Web中 。 第一個瀏覽器WorldWideWeb (記住CSS尚未發明 ) 以這種方式顯示網頁 。 有趣的事實:有史以來第二個瀏覽器, 行模式瀏覽器 (基于終端的瀏覽器)在黑暗中呈綠色。 如今,網頁和Web應用程序通常在淺色背景上使用深色文字進行設計,這是一個基線假設,該假設也已硬編碼在用戶代理樣式表中,包括Chrome瀏覽器 。

Image for post
Source)來源 )

The days of CRTs are long over. Content consumption and creation has shifted to mobile devices that use backlit LCD or energy-saving AMOLED screens. Smaller and more transportable computers, tablets, and smartphones led to new usage patterns. Leisure tasks like web browsing, coding for fun, and high-end gaming frequently happen after-hours in dim environments. People even enjoy their devices in their beds at night-time. The more people use their devices in the dark, the more the idea of going back to the roots of light-on-dark becomes popular.

CRT的時代已經過去了。 內容的消費和創作已經轉移到使用背光LCD或節能AMOLED屏幕的移動設備。 體積更小,更便于攜帶的計算機,平板電腦和智能手機帶來了新的使用方式。 在昏暗的環境中,下班后經常發生諸如瀏覽網頁,娛樂性編碼和高端游戲之類的休閑任務。 人們甚至在夜間都喜歡躺在床上的設備。 在黑暗中使用設備的人越多,回到黑暗中的根源的想法就越受歡迎。

為什么選擇暗模式 (Why dark mode)

出于審美原因的黑暗模式 (Dark mode for aesthetic reasons)

When people get asked why they like or want dark mode, the most popular response is that “it’s easier on the eyes,”followed by “it’s elegant and beautiful.” Apple in their Dark Mode developer documentation explicitly writes: “The choice of whether to enable a light or dark appearance is an aesthetic one for most users, and might not relate to ambient lighting conditions.”

當人們被問到為什么喜歡或想要黑暗模式時 ,最受歡迎的回答是“它在眼睛上更容易”,然后是“它優雅而美麗”。 蘋果公司在其黑暗模式開發人員文檔中明確寫道: “對于大多數用戶而言,選擇啟用淺色還是深色外觀是一種美感,并且可能與環境照明條件無關。”

👩?🔬 Read up more on user research regarding why people want dark mode and how they use it.

user閱讀有關用戶研究的更多內容,以了解人們為什么想要暗模式以及如何使用暗模式 。

Image for post
Source)來源 )

暗模式作為輔助工具 (Dark mode as an accessibility tool)

There are also people who actually need dark mode and use it as another accessibility tool, for example, users with low vision. The earliest occurrence of such an accessibility tool I could find is System 7’s CloseView feature, which had a toggle for Black on White and White on Black. While System 7 supported color, the default user interface was still black-and-white.

還有一些人實際上需要暗模式并將其用作另一種可訪問性工具,例如視力不佳的用戶。 我可以找到的最早出現的這種可訪問性工具是System 7的CloseView功能,該功能具有“白底黑字”和“ 白底黑字”的切換功能。 盡管System 7支持顏色,但默認的用戶界面仍為黑白。

These inversion-based implementations demonstrated their weaknesses once color was introduced. User research by Szpiro et al. on how people with low vision access computing devices showed that all interviewed users disliked inverted images, but that many preferred light text on a dark background. Apple accommodates for this user preference with a feature called Smart Invert, which reverses the colors on the display, except for images, media, and some apps that use dark color styles.

一旦引入了顏色,這些基于反轉的實現就證明了它們的弱點。 Szpiro 等人的用戶研究 關于低視力訪問計算設備的人們的看法表明,所有受訪用戶都不喜歡倒置的圖像,但是許多人更喜歡深色背景上的淺色文字。 Apple通過稱為Smart Invert的功能來適應這種用戶偏好,該功能可以反轉顯示屏上的顏色,但圖像,媒體和某些使用深色樣式的應用除外。

A special form of low vision is Computer Vision Syndrome, also known as Digital Eye Strain, which is defined as “the combination of eye and vision problems associated with the use of computers (including desktop, laptop, and tablets) and other electronic displays (e.g. smartphones and electronic reading devices).” It has been proposed that the use of electronic devices by adolescents, particularly at night time, leads to an increased risk of shorter sleep duration, longer sleep-onset latency, and increased sleep deficiency. Additionally, exposure to blue light has been widely reported to be involved in the regulation of circadian rhythm and the sleep cycle, and irregular light environments may lead to sleep deprivation, possibly affecting mood and task performance, according to research by Rosenfield. To limit these negative effects, reducing blue light by adjusting the display color temperature through features like iOS’ Night Shift or Android’s Night Light can help, as well as avoiding bright lights or irregular lights in general through dark themes or dark modes.

低視力的一種特殊形式是計算機視覺綜合癥,也稱為“數字眼疲勞”,其定義為“與使用計算機(包括臺式機,筆記本電腦和平板電腦)和其他電子顯示器(例如智能手機和電子閱讀設備)。” 已經提出 ,青少年,特別是在夜間使用電子設備,會導致睡眠時間縮短,睡眠開始潛伏期延長和睡眠不足的風險增加。 此外, 據 羅森菲爾德(Rosenfield)的研究 ,據報道 ,暴露于藍光與晝夜節律和睡眠周期的調節有關,不規則的光照環境可能導致睡眠不足,從而可能影響情緒和工作表現。 為了限制這些負面影響,通過iOS的Night Shift或Android的Night Night之類的功能來調節顯示器的色溫來減少藍光可以起到幫助作用,并且通常可以通過深色主題或深色模式避免明亮或不規則的燈光。

在AMOLED屏幕上節省暗模式 (Dark mode power savings on AMOLED screens)

Finally, dark mode is known to save a lot of energy on AMOLED screens. Android case studies that focused on popular Google apps like YouTube have shown that the power savings can be up to 60%. The video below has more details on these case studies and the power savings per app.

最后,已知暗模式可在AMOLED屏幕上節省大量能量。 針對YouTube等熱門Google應用的Android案例研究表明,節電效果可高達60%。 以下視頻詳細介紹了這些案例研究以及每個應用的節能功能。

在操作系統中激活暗模式 (Activating dark mode in the operating system)

Now that I have covered the background of why dark mode is such a big deal for many users, let’s review how you can support it.

現在,我已經介紹了為什么暗模式對許多用戶如此重要的背景,讓我們回顧一下如何支持它。

Image for post
Android Q dark theme settings
Android Q黑暗主題設置

Operating systems that support a dark mode or dark theme typically have an option to activate it somewhere in the settings. On macOS X, it’s in the system preference’s General section and called Appearance (screenshot), and on Windows 10, it’s in the Colors section and called Choose your color (screenshot). For Android Q, you can find it under Display as a Dark Theme toggle switch (screenshot), and on iOS 13, you can change the Appearance in the Display & Brightness section of the settings (screenshot).

支持深色模式或深色主題的操作系統通常可以在設置中的某個位置激活它。 在macOS X上,它位于系統偏好設置的“ 常規”部分中,稱為“ 外觀” ( 屏幕截圖 );在Windows 10上,它位于“ 顏色”部分中,名為“選擇顏色” ( 屏幕截圖 )。 對于Android Q,您可以在“ 顯示深色主題”切換開關( 屏幕截圖 )下找到它,而在iOS 13上,可以在設置的“ 顯示與亮度”部分( 屏幕截圖 )中更改外觀

prefers-color-scheme媒體查詢 (The prefers-color-scheme media query)

One last bit of theory before I get going. Media queries allow authors to test and query values or features of the user agent or display device, independent of the document being rendered. They are used in the CSS @media rule to conditionally apply styles to a document, and in various other contexts and languages, such as HTML and JavaScript. Media Queries Level 5 introduces so-called user preference media features, that is, a way for sites to detect the user's preferred way to display content.

在我開始之前的最后一點理論。 媒體查詢使作者可以獨立于要呈現的文檔來測試和查詢用戶代理或顯示設備的值或功能。 它們在CSS @media規則中用于有條件地將樣式應用于文檔以及各種其他上下文和語言,例如HTML和JavaScript。 媒體查詢級別5引入了所謂的用戶首選項媒體功能,即站點檢測用戶偏愛的顯示內容的方式。

?? An established user preference media feature is prefers-reduced-motion that lets you detect the desire for less motion on a page. I have written about prefers-reduced-motion before.

established?建立的用戶首選項媒體功能是“ prefers-reduced-motion ,使您可以檢測到頁面上希望減少運動的愿望。 我以前寫過關于“ prefers-reduced-motion

The prefers-color-scheme media feature is used to detect if the user has requested the page to use a light or dark color theme. It works with the following values:

prefers-color-scheme媒體功能用于檢測用戶是否已請求頁面使用淺色或深色主題。 它適用于以下值:

  • no-preference: Indicates that the user has made no preference known to the system. This keyword value evaluates as false in the boolean context.

    no-preference :指示用戶不知道系統的任何首選項。 在布爾上下文中,此關鍵字值的值為false

  • light: Indicates that the user has notified the system that they prefer a page that has a light theme (dark text on light background).

    light :表明用戶已通知系統,他們希望頁面具有淺色主題(淺色背景上的深色文本)。

  • dark: Indicates that the user has notified the system that they prefer a page that has a dark theme (light text on dark background).

    dark :表示用戶已通知系統他們偏愛具有深色主題的頁面(深色背景上的淺色文本)。

支持暗模式 (Supporting dark mode)

找出瀏覽器是否支持暗模式 (Finding out if dark mode is supported by the browser)

As dark mode is reported through a media query, you can easily check if the current browser supports dark mode by checking if the media query prefers-color-schemematches at all. Note how I don't include any value, but purely check if the media query alone matches.

由于通過媒體查詢報告了暗模式,因此您可以通過檢查媒體查詢是否完全prefers-color-scheme匹配來輕松檢查當前瀏覽器是否支持暗模式。 請注意,我不包含任何值,而只是檢查媒體查詢是否匹配。

if (window.matchMedia('(prefers-color-scheme)').media !== 'not all') {
console.log('🎉 Dark mode is supported');
}

At the time of writing, prefers-color-scheme is supported on both desktop and mobile (where available) by Chrome and Edge as of version 76, Firefox as of version 67, and Safari as of version 12.1 on macOS and as of version 13 on iOS. For all other browsers, you can check the Can I use support tables.

在撰寫本文時,Chrome和Edge自版本76起支持Firefox和臺式機(自版本67起)的Firefox,自macOS和版本13起(版本12.1)的Safari在臺式機和移動設備(如果有)上均支持prefers-color-scheme在iOS上。 對于所有其他瀏覽器,您可以檢查可以使用支持表 。

There is a custom element <dark-mode-toggle>available that adds dark mode support to older browsers. I write about it further down in this article.

有一個自定義元素<dark-mode-toggle>可用于向較舊的瀏覽器添加暗模式支持。 我將在本文的下半部分對此進行介紹 。

實踐中的暗模式 (Dark mode in practice)

Let’s finally see how supporting dark mode looks like in practice. Just like with the Highlander, with dark mode there can be only one: dark or light, but never both! Why do I mention this? Because this fact should have an impact on the loading strategy. Please don’t force users to download CSS in the critical rendering path that is for a mode they don’t currently use. To optimize load speed, I have therefore split my CSS for the example app that shows the following recommendations in practice into three parts in order to defer non-critical CSS:

最后,讓我們看看在實踐中如何支持深色模式。 就像使用Highlander一樣 ,在黑暗模式下,只能有一個 :黑暗或明亮,但不能同時存在! 我為什么要提這個? 因為這個事實應該會對加載策略產生影響。 請不要強迫用戶在關鍵渲染路徑中下載CSS,這是他們當前不使用的模式。 因此,為了優化加載速度,我將示例應用程序CSS拆分為三個部分,以便在實踐中顯示以下建議,以延遲非關鍵CSS :

  • style.css that contains generic rules that are used universally on the site.

    style.css ,其中包含在網站上普遍使用的通用規則。

  • dark.css that contains only the rules needed for dark mode.

    dark.css ,僅包含黑暗模式所需的規則。

  • light.css that contains only the rules needed for light mode.

    light.css僅包含燈光模式所需的規則。

加載策略 (Loading strategy)

The two latter ones, light.css and dark.css, are loaded conditionally with a <link media> query. Initially, not all browsers will support prefers-color-scheme(detectable using the pattern above), which I deal with dynamically by loading the default light.css file via a conditionally inserted <link rel="stylesheet">element in a minuscule inline script (light is an arbitrary choice, I could also have made dark the default fallback experience). To avoid a flash of unstyled content, I hide the content of the page until light.css has loaded.

后面兩個, light.cssdark.css ,有條件地通過<link media>查詢加載。 最初, 并不是所有的瀏覽器都支持 prefers-color-scheme (可以使用上述模式檢測到),我通過在有條件的內聯中有條件插入的<link rel="stylesheet">元素加載默認的light.css文件來動態處理腳本(淺色是任意選擇,我也可以將深色作為默認的后備體驗)。 為了避免顯示未樣式化的內容 ,我將頁面的內容隱藏起來,直到light.css加載light.css

<script>
// If `prefers-color-scheme` is not supported, fall back to light mode.
// In this case, light.css will be downloaded with `highest` priority.
if (window.matchMedia('(prefers-color-scheme)').media === 'not all') {
document.documentElement.style.display = 'none';
document.head.insertAdjacentHTML(
'beforeend',
'<link rel="stylesheet" href="/light.css" onload="document.documentElement.style.display = ``">'
);
}
</script>
<!--
Conditionally either load the light or the dark stylesheet. The matching file
will be downloaded with `highest`, the non-matching file with `lowest`
priority. If the browser doesn't support `prefers-color-scheme`, the media
query is unknown and the files are downloaded with `lowest` priority (but
above I already force `highest` priority for my default light experience).
-->
<link rel="stylesheet" href="/dark.css" media="(prefers-color-scheme: dark)">
<link rel="stylesheet" href="/light.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)">
<!-- The main stylesheet -->
<link rel="stylesheet" href="/style.css">

樣式表架構 (Stylesheet architecture)

I make maximum use of CSS variables, this allows my generic style.css to be, well, generic, and all the light or dark mode customization happens in the two other files dark.css and light.css. Below you can see an excerpt of the actual styles, but it should suffice to convey the overall idea. I declare two variables, -?-?color and -?-?background-color that essentially create a dark-on-light and a light-on-dark baseline theme.

我最大限度地利用了CSS變量 ,這使我的通用style.css成為通用的,所有亮或暗模式自定義都發生在另外兩個文件dark.csslight.css 。 在下面可以看到實際樣式的摘錄,但足以傳達總體思想。 我聲明了兩個變量-?-?color-?-?background-color ,它們實際上創建了暗上暗上基線主題。

/* light.css: 👉 dark-on-light */
:root {
--color: rgb(5, 5, 5);
--background-color: rgb(250, 250, 250);
}/* dark.css: 👉 light-on-dark */
:root {
--color: rgb(250, 250, 250);
--background-color: rgb(5, 5, 5);
}

In my style.css, I then use these variables in the body { … } rule. As they are defined on the :root CSS pseudo-class—a selector that in HTML represents the <html> element and is identical to the selector html, except that its specificity is higher—they cascade down, which serves me for declaring global CSS variables.

然后,在我的style.css ,在body { … }規則中使用這些變量。 正如它們在:root CSS偽類上定義的那樣-一個選擇器,在HTML中代表<html>元素,并且與選擇器html相同,只是它的特殊性更高-它們級聯向下,這有助于我聲明全局CSS變量。

/* style.css */
:root {
color-scheme: light dark;
}body {
color: var(--color);
background-color: var(--background-color);
}

In the code sample above, you will probably have noticed a property color-scheme with the space-separated value light dark.

在上面的代碼示例中,您可能會注意到一個屬性color-scheme其中的空格分隔值為light dark

Warning: The color-scheme property is still in development and it might not work as advertised, full support in Chrome will come later this year.

警告: color-scheme屬性仍在開發中 ,可能無法像廣告中所述正常工作,Chrome將于今年晚些時候全面支持。

This tells the browser which color themes my app supports and allows it to activate special variants of the user agent stylesheet, which is useful to, for example, let the browser render form fields with a dark background and light text, adjust the scrollbars, or to enable a theme-aware highlight color. The exact details of color-scheme are specified in CSS Color Adjustment Module Level 1.

這會告訴瀏覽器我的應用支持哪種顏色主題,并允許它激活用戶代理樣式表的特殊變體,例如,這對于使瀏覽器呈現深色背景和淺色文本的表單字段,調整滾動條或啟用主題感知突出顯示顏色。 color-scheme的確切詳細信息在CSS顏色調整模塊級別1中指定。

🌒 Read up more on what color-scheme actually does.

🌒了解更多的關于什么 color-scheme 實際執行 。

Everything else is then just a matter of defining CSS variables for things that matter on my site. Semantically organizing styles helps a lot when working with dark mode. For example, rather than -?-?highlight-yellow, consider calling the variable -?-?accent-color, as "yellow" may actually not be yellow in dark mode or vice versa. Below is an example of some more variables that I use in my example.

然后,其他所有事情都只是為我的網站上重要的事情定義CSS變量。 在黑暗模式下工作時,語義上組織樣式很有幫助。 例如,可以考慮調用變量-?-?accent-color而不是-?-?highlight-yellow ,因為在黑暗模式下“ yellow”實際上可能不是黃色,反之亦然。 以下是在示例中使用的一些其他變量的示例。

/* dark.css */
:root {
--color: rgb(250, 250, 250);
--background-color: rgb(5, 5, 5);
--link-color: rgb(0, 188, 212);
--main-headline-color: rgb(233, 30, 99);
--accent-background-color: rgb(0, 188, 212);
--accent-color: rgb(5, 5, 5);
}/* light.css */
:root {
--color: rgb(5, 5, 5);
--background-color: rgb(250, 250, 250);
--link-color: rgb(0, 0, 238);
--main-headline-color: rgb(0, 0, 192);
--accent-background-color: rgb(0, 0, 238);
--accent-color: rgb(250, 250, 250);
}

完整的例子 (Full example)

In the following Glitch embed, you can see the complete example that puts the concepts from above into practice. Try toggling dark mode in your particular operating system’s settings and see how the page reacts.

在下面的Glitch嵌入中,您可以看到將以上概念付諸實踐的完整示例。 嘗試在特定操作系統的設置中切換暗模式,然后查看頁面的React。

加載影響 (Loading impact)

When you play with this example, you can see why I load my dark.css and light.css via media queries. Try toggling dark mode and reload the page: the particular currently non-matching stylesheets are still loaded, but with the lowest priority, so that they never compete with resources that are needed by the site right now.

當您處理此示例時,您可以看到為什么我通過媒體查詢加載dark.csslight.css原因。 嘗試切換暗模式并重新加載頁面:特定的當前不匹配的樣式表仍會被加載,但是優先級最低,因此它們永遠不會與網站當前所需的資源競爭。

😲 Read up more on why browsers download stylesheets with non-matching media queries.

😲有關為何瀏覽器下載帶有不匹配媒體查詢的樣式表的信息 。

Image for post
Site in light mode loads the dark mode CSS with lowest priority.
處于亮模式的站點將以最低優先級加載暗模式CSS。
Image for post
Site in dark mode loads the light mode CSS with lowest priority.
處于暗模式的站點將以最低優先級加載亮模式CSS。
Image for post
prefers-color-scheme loads the dark mode CSS with lowest priority.prefers-color-scheme的瀏覽器上,網站處于默認的淺色模式時,將以最低優先級加載深色模式CSS。

對暗模式更改做出React (Reacting on dark mode changes)

Like any other media query change, dark mode changes can be subscribed to via JavaScript. You can use this to, for example, dynamically change the favicon of a page or change the <meta name="theme-color"> that determines the color of the URL bar in Chrome. The full example above shows this in action, in order to see the theme color and favicon changes, open the demo in a separate tab.

與其他媒體查詢更改一樣,可以通過JavaScript訂閱暗模式更改。 您可以使用它來例如動態更改頁面的圖標或更改確定Chrome中URL欄顏色的<meta name="theme-color"> 。 上面的完整示例通過實際操作展示了這一點,為了查看主題顏色和圖標圖標的變化,請在單獨的選項卡中打開演示 。

const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
darkModeMediaQuery.addListener((e) => {
const darkModeOn = e.matches;
console.log(`Dark mode is ${darkModeOn ? '🌒 on' : '?? off'}.`);
});

暗模式最佳實踐 (Dark mode best practices)

避免純白色 (Avoid pure white)

A small detail you may have noticed is that I don’t use pure white. Instead, to prevent glowing and bleeding against the surrounding dark content, I choose a slightly darker white. Something like rgb(250, 250, 250) works well.

您可能已經注意到的一個小細節是我不使用純白色。 相反,為了防止因周圍的深色內容發光和滲色,我選擇了稍深的白色。 像rgb(250, 250, 250) 250,250,250)這樣的東西效果很好。

重新使攝影圖像變色和變暗 (Re-colorize and darken photographic images)

If you compare the two screenshots below, you will notice that not only the core theme has changed from dark-on-light to light-on-dark, but that also the hero image looks slightly different. My user research has shown that the majority of the surveyed people prefer slightly less vibrant and brilliant images when dark mode is active. I refer to this as re-colorization.

如果你比較下面兩張截圖,你會發現,不僅是核心主題已經改變,從黑暗的光光的黑暗 ,但也主人公圖像看起來略有不同。 我的用戶研究表明,當啟用暗模式時,大多數被調查的人更喜歡活力和明亮度稍差的圖像。 我將其稱為重新著色

Image for post
Hero image slightly darkened in dark mode.
英雄圖像在黑暗模式下略微變暗。
Image for post
Regular hero image in light mode.
燈光模式下的常規英雄形象。

Re-colorization can be achieved through a CSS filter on my images. I use a CSS selector that matches all images that don’t have .svg in their URL, the idea being that I can give vector graphics (icons) a different re-colorization treatment than my images (photos), more about this in the next paragraph. Note how I again use a CSS variable, so I can later on flexibly change my filter.

可以通過我的圖像上CSS過濾器實現重新著色。 我使用一個CSS選擇器來匹配所有URL中沒有.svg圖像,其想法是我可以給矢量圖形(圖標)一種不同于我的圖像(照片)的重新著色處理,有關更多信息,請參見下一段 。 注意如何再次使用CSS變量 ,以便以后可以靈活更改過濾器。

🎨 Read up more on user research regarding re-colorization preferences with dark mode.

dark有關暗模式下重新著色首選項的用戶研究 。

As re-colorization is only needed in dark mode, that is, when dark.css is active, there are no corresponding rules in light.css.

作為重新著色只需要在黑暗模式,即,當dark.css是積極的,也有在沒有相應的規則light.css

/* dark.css */
--image-filter: grayscale(50%);img:not([src*=".svg"]) {
filter: var(--image-filter);
}

使用JavaScript自定義暗模式的重新著色強度 (Customizing dark mode re-colorization intensities with JavaScript)

Not everyone is the same and people have different dark mode needs. By sticking to the re-colorization method described above, I can easily make the grayscale intensity a user preference that I can change via JavaScript, and by setting a value of 0%, I can also disable re-colorization completely. Note that document.documentElementprovides a reference to the root element of the document, that is, the same element I can reference with the :rootCSS pseudo-class.

并非每個人都是一樣的,人們對黑暗模式的需求也不同。 通過堅持上述的重新著色方法,我可以輕松地將灰度強度設置為可以通過JavaScript更改的用戶偏好,并且通過將值設置為0% ,我還可以完全禁用重新著色。 請注意, document.documentElement提供了對document.documentElement根元素的引用,即,我可以使用:root CSS偽類引用的元素相同。

const filter = 'grayscale(70%)';
document.documentElement.style.setProperty('--image-filter', value);

反轉矢量圖形和圖標 (Invert vector graphics and icons)

For vector graphics — that in my case are used as icons that I reference via <img> elements—I use a different re-colorization method. While research has shown that people don't like inversion for photos, it does work very well for most icons. Again I use CSS variables to determine the inversion amount in the regular and in the :hover state.

對于矢量圖形(在本例中用作通過<img>元素引用的圖標),我使用了不同的重新著色方法。 盡管研究表明人們不喜歡照片的倒置,但對于大多數圖標來說,倒置效果確實很好。 同樣,我使用CSS變量來確定常規和:hover狀態下的反轉量。

Image for post
Icons are inverted in dark mode.
圖標在黑暗模式下反轉。
Image for post
Regular icons in light mode.
燈光模式下的常規圖標。

Note how again I only invert icons in dark.css but not in light.css, and how :hover gets a different inversion intensity in the two cases to make the icon appear slightly darker or slightly brighter, dependent on the mode the user has selected.

請注意,我如何再次僅在dark.css反轉圖標,而不是在light.css反轉圖標,以及:hover在兩種情況下如何獲得不同的反轉強度,以使圖標顯得更暗或更亮,具體取決于用戶選擇的模式。

/* dark.css */
--icon-filter: invert(100%);
--icon-filter_hover: invert(40%);img[src*=".svg"] {
filter: var(--icon-filter);
}/* light.css */
--icon-filter_hover: invert(60%);/* style.css */
img[src*=".svg"]:hover {
filter: var(--icon-filter_hover);
}

currentColor用于內聯SVG (Use currentColor for inline SVGs)

For inline SVG images, instead of using inversion filters, you can leverage the currentColor CSS keyword that represents the value of an element's color property. This lets you use the color value on properties that do not receive it by default. Conveniently, if currentColor is used as the value of the SVG fill or strokeattributes, it instead takes its value from the inherited value of the color property. Even better: this also works for <svg><use href="…"></svg>, so you can have separate resources and currentColor will still be applied in context. Please note that this only works for inline or <use href="…"> SVGs, but not SVGs that are referenced as the src of an image or somehow via CSS. You can see this applied in the demo below.

對于嵌入式 SVG圖像,您可以使用currentColor CSS關鍵字來表示元素的color屬性的值,而不必使用反轉濾鏡 。 這使您可以在默認情況下不接收color屬性上使用color值。 方便地,如果將currentColor用作SVG fillstroke 屬性的值,則它將從color屬性的繼承值中獲取其值。 更好的是:這也適用于<svg><use href="…"></svg> ,因此您可以擁有單獨的資源,并且currentColor仍將應用在上下文中。 請注意,這僅適用于內聯<use href="…"> SVG,但不適用于被稱為圖像src或通過CSS引用的SVG。 您可以在下面的演示中看到這一點。

<!-- Some inline SVG -->
<svg xmlns="http://www.w3.org/2000/svg"
stroke="currentColor"
>
[…]
</svg>

模式之間的平滑過渡 (Smooth transitions between modes)

Switching from dark mode to light mode or vice versa can be smoothed thanks to the fact that both color and background-color are animatable CSS properties. Creating the animation is as easy as declaring two transitions for the two properties. The example below illustrates the overall idea, you can experience it live in thedemo.

由于colorbackground-color都是可動畫CSS屬性 ,因此可以平滑地從暗模式切換到亮模式,反之亦然。 創建動畫就像聲明兩個屬性的兩個transition一樣容易。 下面的示例說明了總體思路,您可以在演示中現場體驗它。

body {
--duration: 0.5s;
--timing: ease; color: var(--color);
background-color: var(--background-color); transition:
color var(--duration) var(--timing),
background-color var(--duration) var(--timing);
}

黑暗模式下的美術指導 (Art direction with dark mode)

While for loading performance reasons in general I recommend to exclusively work with prefers-color-scheme in the media attribute of <link> elements (rather than inline in stylesheets), there are situations where you actually may want to work with prefers-color-scheme directly inline in your HTML code. Art direction is such a situation. On the web, art direction deals with the overall visual appearance of a page and how it communicates visually, stimulates moods, contrasts features, and psychologically appeals to a target audience.

雖然通常出于加載性能的原因,我建議在<link>元素的media屬性中(而不是在樣式表中以內聯方式)僅與prefers-color-scheme一起使用,但在某些情況下,您實際上可能希望使用prefers-color-scheme直接內聯到您HTML代碼中。 藝術指導就是這種情況。 在網絡上,藝術指導處理頁面的整體視覺外觀,以及頁面如何在視覺上進行溝通,激發情緒,對比功能并在心理上吸引目標受眾。

With dark mode, it’s up to the judgment of the designer to decide what is the best image at a particular mode and whether re-colorization of images is maybe not good enough. If used with the <picture> element, the <source> of the image to be shown can be made dependent on the media attribute. In the example below, I show the Western hemisphere for dark mode, and the Eastern hemisphere for light mode or when no preference is given, defaulting to the Eastern hemisphere in all other cases. This is of course purely for illustrative purposes. Toggle dark mode on your device to see the difference.

在暗模式下,取決于設計者的判斷,以決定在特定模式下什么是最佳圖像,以及圖像的重新著色是否可能不夠好。 如果與<picture>元素一起使用,則可以根據media屬性使要顯示的圖像的<source> 。 在下面的示例中,我顯示了暗模式下的西半球,而亮模式下或沒有給出優先級時的東半球,在所有其他情況下默認為東半球。 當然,這純粹是出于說明目的。 在您的設備上切換暗模式即可查看區別。

<picture>
<source srcset="western.webp" media="(prefers-color-scheme: dark)">
<source srcset="eastern.webp" media="(prefers-color-scheme: light), (prefers-color-scheme: no-preference)">
<img src="eastern.webp">
</picture>

暗模式,但添加退出 (Dark mode, but add an opt-out)

As mentioned in the why dark mode section above, dark mode is an aesthetic choice for most users. In consequence, some users may actually like to have their operating system UI in dark, but still prefer to see their webpages the way they are used to seeing them. A great pattern is to initially adhere to the signal the browser sends through prefers-color-scheme, but to then optionally allow users to override their system-level setting.

如上面的“ 為何選擇暗模式”部分所述,暗模式是大多數用戶的美學選擇。 因此,某些用戶可能實際上希望將其操作系統UI設置為黑暗,但仍希望以習慣于查看它們的方式來查看其網頁。 一個很好的模式是最初遵循瀏覽器通過prefers-color-scheme發送的信號,然后有選擇地允許用戶覆蓋其系統級設置。

<dark-mode-toggle>自定義元素 (The <dark-mode-toggle> custom element)

You can of course create the code for this yourself, but you can also just use a ready-made custom element (web component) that I have created right for this purpose. It’s called <dark-mode-toggle> and it adds a toggle (dark mode: on/off) or a theme switcher (theme: light/dark) to your page that you can fully customize. The demo below shows the element in action (oh, and I have also 🤫 silently snuck it in all of the other examples above).

您當然可以自己為此創建代碼,但是也可以僅使用我為此目的而創建的現成的自定義元素(Web組件)。 它稱為<dark-mode-toggle> ,它為您的頁面添加了可以完全自定義的切換按鈕(暗模式:開/關)或主題切換器(主題:亮/暗)。 下面的演示展示了正在運行的元素(哦,在上面的所有其他 示例中 ,我還默默地隱藏了該元素)。

<dark-mode-toggle
legend="Theme Switcher"
appearance="switch"
dark="Dark"
light="Light"
remember="Remember this"
></dark-mode-toggle>
Image for post
<dark-mode-toggle> in light mode.<dark-mode-toggle>
Image for post
<dark-mode-toggle> in dark mode.<dark-mode-toggle>

Try clicking or tapping the dark mode controls in the upper right corner in the demo below. If you check the checkbox in the third and the fourth control, see how your mode selection is remembered even when you reload the page. This allows your visitors to keep their operating system in dark mode, but enjoy your site in light mode or vice versa.

嘗試單擊或點擊下面演示中右上角的黑暗模式控件。 如果選中第三個和第四個控件中的復選框,則即使重新加載頁面,也將了解如何記住模式選擇。 這樣,您的訪問者可以將其操作系統保持在暗模式下,而在光模式下則可以欣賞您的網站,反之亦然。

結論 (Conclusions)

Working with and supporting dark mode is fun and opens up new design avenues. For some of your visitors it can be the difference between not being able to handle your site and being a happy user. There are some pitfalls and careful testing is definitely required, but dark mode is definitely a great opportunity for you to show that you care about all of your users. The best practices mentioned in this post and helpers like the <dark-mode-toggle> custom element should make you confident in your ability to create an amazing dark mode experience. Let me know on Twitterwhat you create and if this post was useful or also suggestions for improving it. Thanks for reading! 🌒

使用并支持黑暗模式很有趣,并且開辟了新的設計途徑。 對于您的某些訪問者而言,可能是無法處理您的網站與成為滿意的用戶之間的區別。 有一些陷阱,絕對需要仔細測試,但是暗模式絕對是您展示自己關心所有用戶的絕佳機會。 這篇文章中提到的最佳實踐以及<dark-mode-toggle>自定義元素之類的幫助程序應該使您對創建驚人的黑暗模式體驗的能力充滿信心。 讓我在Twitter上知道您創建的內容以及該帖子是否有用,或者還有改進建議。 謝謝閱讀! 🌒

相關鏈接 (Related links)

Resources for the prefers-color-scheme media query:

prefers-color-scheme媒體查詢的資源:

  • Chrome Platform Status page

    Chrome平臺狀態頁面

  • Chromium bug

    Chrome蟲

  • Media Queries Level 5 spec

    媒體查詢5級規范

Resources for the color-scheme meta tag and CSS property:

color-scheme元標記和CSS屬性的資源:

  • Chrome Platform Status page

    Chrome平臺狀態頁面

  • Chromium bug

    Chrome蟲

  • CSS Color Adjustment Module Level 1 spec

    CSS顏色調整模塊1級規格

  • CSS WG GitHub Issue for the meta tag and the CSS property

    meta標簽和CSS屬性CSS WG GitHub問題

  • HTML WHATWG GitHub Issue for the meta tag

    meta標簽HTML WHATWG GitHub問題

General dark mode links:

常規暗模式鏈接:

  • Material Design — Dark Theme

    材質設計-黑暗主題

  • Dark Mode in Web Inspector

    Web檢查器中的暗模式

  • Dark Mode Support in WebKit

    WebKit中的暗模式支持

  • Apple Human Interface Guidelines — Dark Mode

    蘋果人機界面指南-暗模式

Background research articles for this post:

這篇文章的背景研究文章:

  • What Does Dark Mode’s “supported-color-schemes” Actually Do? 🤔

    深色模式的“支持的顏色方案”實際上是做什么的? 🤔

  • Let there be darkness! 🌚 Maybe…

    讓那里黑暗! 🌚也許...

  • Re-Colorization for Dark Mode

    暗模式下重新著色

致謝 (Acknowledgements)

The prefers-color-scheme media feature, the color-scheme CSS property, and the related meta tag are the implementation work of 👏 Rune Lillesveen. Rune is also a co-editor of the CSS Color Adjustment Module Level 1spec. I would like to 🙏 thank Lukasz Zbylut, Rowan Merewood, Chirag Desai, and Rob Dodson for their thorough reviews of this article. The loading strategy is the brainchild of Jake Archibald. Emilio Cobos álvarez has pointed me to the correct prefers-color-schemedetection method. The tip with referenced SVGs and currentColor came from Timothy Hatcher. Finally, I am thankful to the many anonymous participants of the various user studies that have helped shape the recommendations in this article. Hero image by Nathan Anderson.

prefers-color-scheme媒體功能, color-scheme CSS屬性以及相關的meta標簽是👏Rune Lillesveen的實現工作。 符文也是CSS顏色調整模塊1級規范的共同編輯。 我要感謝Lukasz Zbylut , Rowan Merewood , Chirag Desai和Rob Dodson對本文的詳盡評論。 加載策略是Jake Archibald的創意。 Emilio Cobosálvarez向我指出了正確的prefers-color-scheme檢測方法。 引用了SVG和currentColor的技巧來自Timothy Hatcher 。 最后,我感謝各種用戶研究的許多匿名參與者,這些參與者幫助塑造了本文中的建議。 內森·安德森 ( Nathan Anderson)的英雄形象。

進一步閱讀 (Further Reading)

翻譯自: https://medium.com/dev-channel/hello-darkness-my-old-friend-48a97ab4379a

我在黑暗中看到你眼中的月光

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/274947.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/274947.shtml
英文地址,請注明出處:http://en.pswp.cn/news/274947.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ant 實現批量打包android應用

很多的應用中需要加上應用推廣的統計&#xff0c;如果一個一個的去生成不同渠道包的應用&#xff0c;效率低不說&#xff0c;還有可能不小心弄錯了分發渠道&#xff0c;使用ant可以批量生成應用。一、添加渠道包信息為了統計渠道信息&#xff0c;就不得不在程序的某個地方加入渠…

Element Plus 正式版發布啦!

大家好&#xff0c;我是若川。祝大家新年快樂&#xff0c;開工大吉。公眾號回復「紅包」可以領取源碼共讀紅包封面。持續組織了6個月源碼共讀活動&#xff0c;感興趣的可以點此加我微信 ruochuan12 參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。同時…

大型網站技術架構(一)大型網站架構演化

2019獨角獸企業重金招聘Python工程師標準>>> 看完了有一本書&#xff0c;就應該有所收獲&#xff0c;有所總結&#xff0c;最近把《大型網站技術架構》一書給看完了&#xff0c;給人的印象實在深刻&#xff0c;再加上之前也搞過書本上講的反向代理和負載均衡以及ses…

永不示弱_永不過時的網頁設計:今天和2000年的在線投資組合

永不示弱重點 (Top highlight)Philippe Starck, a renowned industrial designer, once said:著名的工業設計師Philippe Starck曾經說過&#xff1a; “A designer has a duty to create timeless design. To be timeless you have to think really far into the future, not …

如何使用 React 創建一個作品集網站

大家好&#xff0c;我是若川。持續組織了6個月源碼共讀活動&#xff0c;感興趣的可以點此加我微信 ruochuan12 參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。今天&#xff0c;你…

博弈論入門 HDU 1850

Problem Description 一年在外 父母時刻牽掛春節回家 你能做幾天好孩子嗎寒假里嘗試做做下面的事情吧陪媽媽逛一次菜場悄悄給爸爸買個小禮物主動地 強烈地 要求洗一次碗某一天早起 給爸媽用心地做回早餐如果愿意 你還可以和爸媽說咱們玩個小游戲吧 ACM課上學的呢&#xff5e;下…

新的一年,如何高效學習前端前沿知識~

今天強烈推薦一些互聯網行業內優質技術公眾號&#xff0c;互聯網人大部分都關注了&#xff0c;包括目前主流的公司技術團隊號&#xff0c;技術社區號&#xff0c;個人技術號&#xff0c;這些號行業深耕已久&#xff0c;會給你帶來事半功倍的效果。公眾號那么多&#xff0c;文章…

RabbitMQ學習總結(7)——Spring整合RabbitMQ實例

2019獨角獸企業重金招聘Python工程師標準>>> 1.RabbitMQ簡介 RabbitMQ是流行的開源消息隊列系統&#xff0c;用erlang語言開發。RabbitMQ是AMQP&#xff08;高級消息隊列協議&#xff09;的標準實現。 官網&#xff1a;http://www.rabbitmq.com/ 2.Spring集成Rabbi…

UIScrollView實現不全屏分頁的小技巧

瀏覽一系列圖片時&#xff0c;我們會經常使用UIScrollView來進行實現&#xff0c;因為其自帶的pagingEnabled屬性&#xff0c;可以非常方便的自動支持手勢左右輕掃切換切換頁面。pagingEnabled不過最近做的一個產品&#xff0c;設計的效果有所不同&#xff0c;希望每一頁圖片的…

談談對java中分層的理解_讓我們談談網頁設計中的卡片設計

談談對java中分層的理解“I want a card”, this is the first demand point that the customer said in the last issue when talking to me about demand. There is no doubt that the card type is excellent for both PC and mobile phones. From online shopping malls to…

1-jdk的安裝與配置

1- Jvm、jdk、jre之間的關系 JVM&#xff1a;Java虛擬機&#xff0c;保證java程序跨平臺。&#xff08;Java Virtual Machine&#xff09;JRE&#xff1a; Java運行環境&#xff0c;包含JVM和核心類庫。如果只是想運行java程序&#xff0c;只要安裝JRE即可。&#xff08;Java R…

來自未來,2022 年的前端人都在做什么?

大家好&#xff0c;我是若川。持續組織了6個月源碼共讀活動&#xff0c;感興趣的可以點此加我微信 ruochuan12 參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。來自上帝視角的總覽…

模擬

狀態壓縮 uva 12368 - Candles 2011 - Dhaka 1 #include<stdio.h> 2 #include<string.h> 3 #include<iostream> 4 #include<string> 5 #include<algorithm> 6 #include<math.h> 7 #include<map> 8 #include<queue> 9 using…

qt ui指針和本類對象_您需要了解的有關UI設計的形狀和對象的所有信息

qt ui指針和本類對象重點 (Top highlight)第1部分 (Part 1) So you’re thinking about becoming a UX/UI designer, but are afraid to start? Don’t worry. It’s easier than you think. You only need a solid foundation and a lot of dedication. I can’t help you wi…

移動端h5頁面復制粘貼(兼容到ios9安卓4.0.0)

項目使用jquery框架純h5復制粘貼解決了iscroll4阻止所有默認事件&#xff0c;長按無法彈出復制菜單項目需要寫一個上拉加載頁面&#xff0c;頁面中的物流信息需要可復制粘貼&#xff0c;同時需要兼容到ios9和安卓4.0.0, 經過大量搜索&#xff0c;最終使用clipboard。代碼如下 &…

2021 大前端技術回顧及未來展望

大家好&#xff0c;我是若川。持續組織了6個月源碼共讀活動&#xff0c;感興趣的可以點此加我微信 ruochuan12 參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。歷史面試系列2021 …

最近想讀的書想做的事

越來越多了&#xff0c;但是總是還沒開始&#xff0c;一天拿出一小時&#xff0c;周末拿出一上午。加油加油 2012/3/27 C標準庫 C專家編程Expert C Programming Deep C Secrets CodeCraft編程匠藝&#xff1a;編寫卓越的代碼 代碼之美 重看 編程珠璣 編程卓越之道 卷1 卷2 代碼…

skysat重訪周期_重訪小惡夢

skysat重訪周期You awaken with a start, the nightmare still fogging your mind with terror. Rain falls through cracks in the ceiling above you. The room is sparse, metallic, desolate. Searching the pockets of your yellow raincoat, you find only a cigarette l…

Python這些位運算的妙用,絕對讓你大開眼界

位運算的性能大家想必是清楚的&#xff0c;效率絕對高。相信愛好源碼的同學&#xff0c;在學習閱讀源碼的過程中會發現不少源碼使用了位運算。但是為啥在實際編程過程中應用少呢&#xff1f;想必最大的原因&#xff0c;是較為難懂。不過&#xff0c;在面試的過程中&#xff0c;…

記一次 Vue2 遷移 Vue3 的實踐總結

大家好&#xff0c;我是若川。持續組織了6個月源碼共讀活動&#xff0c;感興趣的可以點此加我微信 ruochuan12 參與&#xff0c;每周大家一起學習200行左右的源碼&#xff0c;共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。歷史面試系列一、V…