如何使用CSS實現黑暗模式主題
实现暗黑模式有两种主要方式:一是使用 prefers-color-scheme 媒体查询自动适配系统偏好,二是通过 JavaScript 添加手动切换功能。1. 使用 prefers-color-scheme 可自动根据用户系统设置应用暗黑主题,无需 JavaScript,只需定义媒体查询内的样式;2. 实现手动切换需定义 light-theme 和 dark-theme CSS 类,添加切换按钮,并用 JavaScript 管理主题状态和 localStorage 保存用户偏好;3. 可结合两者,在页面加载时优先读取 localStorage,若无则根据系统偏好设置初始主题,从而提供智能默认值与用户控制的平衡。通过 CSS 变量和一致的样式管理,可创建流畅且持久的暗黑模式体验,显著提升可用性。
Implementing a dark mode theme with CSS is straightforward and can be done in several ways depending on your needs—whether you want to respect the user’s system preference or let them toggle it manually on your site. Here's how to do both.
Using prefers-color-scheme for automatic dark mode
The easiest way to implement dark mode is by using the prefers-color-scheme
media query. This lets your site automatically switch themes based on the user’s operating system settings.
/* Default (light mode) styles */ body { background-color: white; color: black; } /* Dark mode styles */ @media (prefers-color-scheme: dark) { body { background-color: #121212; color: #e0e0e0; } }
You can extend this to other elements:
.sidebar { background-color: #f4f4f4; color: #333; } @media (prefers-color-scheme: dark) { .sidebar { background-color: #1e1e1e; color: #ccc; } }
This method requires no JavaScript and works immediately when the user loads the page with their system in dark mode.
Adding a manual toggle with CSS and JavaScript
If you want users to manually switch between light and dark themes (regardless of system settings), you’ll need a toggle button and some JavaScript to manage the state.
1. Define CSS classes for themes
Use classes like light-theme
and dark-theme
on the <html>
or <body>
element.
/* Light theme (default) */ .light-theme { --bg-color: white; --text-color: black; } /* Dark theme */ .dark-theme { --bg-color: #121212; --text-color: #e0e0e0; } /* Apply variables */ body { background-color: var(--bg-color); color: var(--text-color); transition: background-color 0.3s, color 0.3s; }
Using CSS custom properties (variables) makes it easier to manage colors across your site.
2. Add a toggle button in HTML
<button id="theme-toggle">Toggle Dark Mode</button>
3. Use JavaScript to switch themes
const toggleButton = document.getElementById('theme-toggle'); const currentTheme = localStorage.getItem('theme') || 'light'; // default to light // Set initial theme document.documentElement.className = currentTheme '-theme'; // Update button text toggleButton.textContent = currentTheme === 'dark' ? 'Switch to Light' : 'Switch to Dark'; // Toggle theme on click toggleButton.addEventListener('click', () => { const isDark = document.documentElement.classList.contains('dark-theme'); const newTheme = isDark ? 'light' : 'dark'; document.documentElement.className = newTheme '-theme'; localStorage.setItem('theme', newTheme); toggleButton.textContent = newTheme === 'dark' ? 'Switch to Light' : 'Switch to Dark'; });
This saves the user’s preference in localStorage
so the theme persists across page reloads.
Optional: Combine both approaches
You can combine system preference detection with manual override:
- On page load, check
localStorage
first. - If no preference is saved, use
prefers-color-scheme
to set the initial theme.
const savedTheme = localStorage.getItem('theme'); const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; const initialTheme = savedTheme || (systemPrefersDark ? 'dark' : 'light'); document.documentElement.className = initialTheme '-theme';
This gives users the best of both worlds: a smart default and full control.
Using CSS variables, media queries, and a bit of JavaScript, you can implement a smooth, persistent dark mode that enhances user experience. The key is consistency in using variables and saving user preferences. Basically, it’s simple to set up and makes a big difference in usability.
以上是如何使用CSS實現黑暗模式主題的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

要更改CSS列表樣式,首先使用list-style-type改變項目符號或編號樣式,1.使用list-style-type設置ul的項目符號為disc、circle或square,ol的編號為decimal、lower-alpha、upper-alpha、lower-roman或upper-roman,2.用list-style:none完全移除標記,3.使用list-style-image:url('bullet.png')替換為自定義圖像,4.通過list-style-position:in

使用CSS創建點狀邊框只需設置border屬性為dotted即可,例如“border:3pxdotted#000”可為元素添加3像素寬的黑色點狀邊框,通過調整border-width可改變點的大小,較寬的邊框產生更大的點,且可單獨為某一邊設置點狀邊框如“border-top:2pxdottedred”,點狀邊框適用於div、input等塊級元素,常用於焦點狀態或可編輯區域以提升可訪問性,需注意顏色對比度,同時區別於dashed的短線樣式,dotted呈現圓形點狀,該特性在所有主流瀏覽器中均被廣泛

使用純CSS創建響應式自動輪播的推薦語滑塊是可行的,只需結合HTML結構、Flexbox佈局和CSS動畫。 2.首先構建包含多個推薦語項的語義化HTML容器,每個.item包含引用內容和作者信息。 3.通過設置父容器display:flex、width:300%(三張幻燈片)並應用overflow:hidden實現橫向排列。 4.利用@keyframes定義從0%到-100%的translateX變換,配合animation:scroll15slinearinfinite實現無縫自動滾動。 5.添加媒體

CSSgradientsprovidesmoothcolortransitionswithoutimages.1.Lineargradientstransitioncolorsalongastraightlineusingdirectionsliketobottomorangleslike45deg,andsupportmultiplecolorstopsforcomplexeffects.2.Radialgradientsradiatefromacentralpointusingcircleo

要創建CSS的玻璃擬態效果,需使用backdrop-filter實現背景模糊,設置半透明背景如rgba(255,255,255,0.1),添加細微邊框和陰影以增強層次感,並確保元素背後有足夠視覺內容;1.使用backdrop-filter:blur(10px)模糊背景內容;2.採用rgba或hsla定義透明背景控制通透程度;3.添加1pxsolidrgba(255,255,255,0.3)邊框及box-shadow提升立體感;4.確保容器具有豐富背景如圖片或紋理以呈現模糊穿透效果;5.為兼容舊瀏

Usebuilt-incursortypeslikepointer,help,ornot-allowedtoprovideimmediatevisualfeedbackfordifferentinteractiveelements.2.ApplycustomcursorimageswiththecursorpropertyusingaURL,optionallyspecifyingahotspotandalwaysincludingafallbacklikeautoorpointer.3.Fol

Grid-template-areaspropertyallowsdevelopspocrockearteeintuitive,ReadableLayoutsByDefiningNemedGridareas; everystringrepresentsarowresentsarowandeashwordeachwordaColumnCell,withGrid-areanamesonamesonameSonemaneMeAnemesonChildEllementsMatchingThoseNoseNementsMatchingTheSoseIntheTemplate,suchans'headerheaderheaderheaderheaderheaderheaderheaderheader for for for for for for

要添加盒陰影,使用box-shadow屬性;1.基本語法為box-shadow:水平偏移垂直偏移模糊半徑擴展半徑顏色內陰影;2.前三個值必填,其餘可選;3.使用rgba()或hsla()實現透明效果;4.正擴展半徑擴大陰影,負值縮小;5.可通過逗號分隔添加多個陰影;6.應避免過度使用,確保在不同背景上測試可見性;該屬性瀏覽器支持良好,合理運用可提升設計質感。
