Define CSS variables and combine prefers-color-scheme to implement dark mode. Set light-color themes through:root, overwrite them as dark colors in @media, use variables to uniformly apply styles, and optionally switch between JavaScript to add transition and contrast optimization experience.
To create a dark mode theme with CSS, you can use a combination of custom properties (CSS variables), the :root selector, and the @media (prefers-color-scheme) rule to detect user system preferences. This approach lets you define both light and dark themes and switch between them smoothly.
Define CSS Variables for Themes
Start by setting up color variables in your CSS for both light and dark modes. Use :root to define global variables, and override them under specific conditions.
- Create variables for background, text, and accent colors.
- Name them logically so they're easy to manage (eg, --bg-color, --text-color).
Example:
:root { --bg-color: #ffffff; --text-color: #333333; --accent-color: #007bff; } @media (prefers-color-scheme: dark) { :root { --bg-color: #121212; --text-color: #f5f5f5; --accent-color: #0a6eff; } }
Apply Variables to Your Styles
Use the defined variables across your stylesheet to ensure consistency. This makes it easy to update styles later and supports dynamic theme switching.
- Apply variables to body, headings, links, buttons, and other common elements.
- Avoid hardcoding colors; stick to variables wherever possible.
Example:
body { background-color: var(--bg-color); color: var(--text-color); transition: background-color 0.3s ease, color 0.3s ease; } a { color: var(--accent-color); }
Support Manual Theme Toggle (Optional)
If you want users to manually switch themes instead of relying on system settings, use a JavaScript toggle that adds a class (like .dark-mode ) to the element, then style accordingly.
- Add a button to trigger the theme change.
- Use JavaScript to toggle a class on the document element.
- Override variables inside the class selector.
CSS:
.dark-mode { --bg-color: #121212; --text-color: #f5f5f5; --accent-color: #0a6eff; }
JavaScript:
document.getElementById('theme-toggle').addEventListener('click', () => { document.documentElement.classList.toggle('dark-mode'); });
Smooth Transitions and Accessibility
Enhance user experience by adding smooth color transitions and ensuring sufficient contrast in both modes.
- Add transition to background and text colors for a fade effect.
- Test contrast ratios to meet accessibility standards (WCAG).
- Respect user preference using prefers-color-scheme .
Basically just set up variables, respond to system preferences or user input, and apply styles consistently. It's not complex but makes a big difference in usability.
The above is the detailed content of How to create a dark mode theme with CSS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

clamp() function realizes responsive font scaling through the minimum, preferred and maximum values; 2. The syntax is clamp (minimum value, preferred value, maximum value), and commonly used rem and vw units; 3. The font takes the minimum value on the small screen, and scales according to vw as the screen increases, and does not exceed the maximum value; 4. Reasonably select the numerical value to ensure readability and avoid being too large or too small; 5. Combining the rem type proportion to improve design consistency.

Use aspect-ratio:1/1 to create a responsive square, and set the aspect ratio in modern browsers; if you need to be compatible with old browsers, you can use padding-top:100% technique to maintain the consistency of width and height by relative units; you can also use vw units to make the square change with the viewport.

1. Open the web page printing interface, click "More Settings" and uncheck "Header and Footer" to remove automatically added URLs, dates and other information. 2. By adding the CSS style of @mediaprint{@page{margin:0}} to the web page code, the default margins and headers and footers can be cleared. 3. Install third-party printing extensions such as PrintEdit, which can edit print content more flexibly and disable the default header and footer.

Use backdrop-filter:blur() to achieve the frosted glass effect, combining rgba transparent background, thin borders and rounded corners, such as .frosted-card{backdrop-filter:blur(10px);background-color:rgba(255,255,255,0.1);border:1pxsolidrgba(255,255,255,0.2);border-radius:12px;padding:20px;}, be sure to ensure that there is content behind the elements and pay attention to browser compatibility.

Define CSS variables and combine prefers-color-scheme to implement dark mode. Set light-color themes through:root, overwrite them as dark colors in @media, use variables to uniformly apply styles, and optionally switch between JavaScript to add transition and contrast optimization experience.

Use the :last-child pseudo-class selector to accurately locate the last child element in the parent container, regardless of its type. For example, li:last-child is used for the last item on the list, and *:last-child is suitable for any ending element. Unlike :last-of-type, :last-child only focuses on whether it is the last child node, while :last-of-type matches the last instance of a particular type. This method is widely supported and is suitable for scenarios such as removing unnecessary margins or highlighting the last item.

Logicalpropertiesenableadaptable,internationallayoutsbyreplacingfixeddirectionswithflow-relativetermslikeblockandinline,ensuringconsistentstylingacrossLTR,RTL,andverticalwritingmodes.

The:emptypseudo-classselectselementswithnocontentorchildren,includingnospacesorlinebreaks;forexample,div:emptystylescompletelyemptydivs,andcombiningitwith::beforecaninsertfallbackmessageslike"Nocontentavailable"toimprovelayouthandlingindyna
