English

Explore the power of CSS media queries and custom properties to create automatic light and dark themes that adapt to user preferences, enhancing accessibility and visual appeal for a global audience.

CSS Light-Dark Function: Automatic Theme Adaptation for a Global Web

In today's globally connected world, websites need to be accessible and visually appealing to users from diverse backgrounds and preferences. One of the most effective ways to achieve this is through automatic theme adaptation, specifically offering both light and dark themes that adjust based on the user's system settings. This blog post will guide you through implementing this functionality using CSS media queries and custom properties, ensuring a seamless and comfortable browsing experience for your international audience.

Why Implement Automatic Light and Dark Themes?

There are several compelling reasons to incorporate automatic theme adaptation into your web projects:

How to Implement Automatic Theme Adaptation with CSS

The core of automatic theme adaptation lies in the prefers-color-scheme media query. This CSS media query allows you to detect the user's preferred color scheme (light or dark) and apply corresponding styles.

Step 1: Define Custom Properties (CSS Variables)

Start by defining custom properties (CSS variables) to store the color values for your light and dark themes. This makes it easy to switch between themes by simply updating the variable values.


:root {
  --background-color: #ffffff; /* Light theme background */
  --text-color: #000000; /* Light theme text */
  --link-color: #007bff; /* Light theme link */
  --button-background-color: #f0f0f0;
  --button-text-color: #000;
}

@media (prefers-color-scheme: dark) {
  :root {
    --background-color: #121212; /* Dark theme background */
    --text-color: #ffffff; /* Dark theme text */
    --link-color: #66b3ff; /* Dark theme link */
    --button-background-color: #333;
    --button-text-color: #fff;
  }
}

In this example, we define variables for background color, text color, link color, and button colors. The :root selector applies these variables to the entire document. The @media (prefers-color-scheme: dark) media query then overrides these variables with dark theme values when the user has set their system to dark mode.

Step 2: Apply Custom Properties to Your Styles

Next, apply these custom properties to your CSS styles to control the appearance of your website elements.


body {
  background-color: var(--background-color);
  color: var(--text-color);
  transition: background-color 0.3s, color 0.3s; /* Smooth transition */
}

a {
  color: var(--link-color);
}

button {
  background-color: var(--button-background-color);
  color: var(--button-text-color);
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

Here, we're using the var() function to access the values of our custom properties. We've also added a transition property to the body element to create a smooth transition between themes.

Step 3: Testing and Refinement

Thoroughly test your implementation across different browsers and operating systems. Modern browsers like Chrome, Firefox, Safari, and Edge fully support the prefers-color-scheme media query. You can switch between light and dark modes in your operating system settings to see the changes reflected in your website.

Advanced Techniques and Considerations

Providing a Manual Theme Switch

While automatic theme adaptation is a great starting point, some users may prefer to manually override their system settings. You can provide a manual theme switch using JavaScript and local storage.

HTML:



JavaScript:


const themeToggle = document.getElementById('theme-toggle');
const body = document.body;

let currentTheme = localStorage.getItem('theme') || 'auto'; // Default to auto

function setTheme(theme) {
  if (theme === 'dark') {
    body.classList.add('dark-theme');
    body.classList.remove('light-theme');
  } else if (theme === 'light') {
    body.classList.add('light-theme');
    body.classList.remove('dark-theme');
  } else {
    body.classList.remove('light-theme', 'dark-theme');
  }
  localStorage.setItem('theme', theme);
  currentTheme = theme;
}

// Apply initial theme on page load
if (currentTheme === 'dark') {
  setTheme('dark');
} else if (currentTheme === 'light') {
  setTheme('light');
} else {
  //If set to auto, allow prefers-color-scheme to decide
}


themeToggle.addEventListener('click', () => {
    if (currentTheme === 'auto'){
        setTheme('light');
    } else if (currentTheme === 'light') {
        setTheme('dark');
    } else {
        setTheme('auto');
    }
});

CSS: Add the following CSS along with the previous CSS. Notice the manual override:


body.light-theme {
  --background-color: #ffffff; /* Light theme background */
  --text-color: #000000; /* Light theme text */
  --link-color: #007bff; /* Light theme link */
  --button-background-color: #f0f0f0;
  --button-text-color: #000;
}

body.dark-theme {
  --background-color: #121212; /* Dark theme background */
  --text-color: #ffffff; /* Dark theme text */
  --link-color: #66b3ff; /* Dark theme link */
  --button-background-color: #333;
  --button-text-color: #fff;
}

This code snippet adds a button that allows users to toggle between light, dark, and automatic themes. The selected theme is stored in local storage so that it persists across page loads.

Handling Images and SVGs

Some images and SVGs may not look good in both light and dark themes. You can use CSS media queries to conditionally display different versions of these assets.


img.light-mode {
  display: block;
}

img.dark-mode {
  display: none;
}

@media (prefers-color-scheme: dark) {
  img.light-mode {
    display: none;
  }

  img.dark-mode {
    display: block;
  }
}

This code snippet shows one image (with class light-mode) in light mode and a different image (with class dark-mode) in dark mode.

Color Palette Considerations for International Audiences

When choosing color palettes for your light and dark themes, be mindful of cultural associations and accessibility considerations. Here are some general guidelines:

Performance Considerations

While implementing automatic theme adaptation is relatively straightforward, it's important to consider the potential impact on performance. Avoid using overly complex CSS selectors or animations that can slow down rendering. Also, ensure that your custom properties are defined efficiently to minimize the overhead of variable lookups.

Here are some best practices for optimizing performance:

Accessibility Best Practices

Ensure your light and dark themes meet accessibility guidelines, such as WCAG (Web Content Accessibility Guidelines). This includes providing sufficient color contrast, using semantic HTML, and ensuring that all interactive elements are keyboard accessible.

Here are some specific accessibility best practices to follow:

Examples Across Different Regions

Consider these examples of how light and dark themes can be tailored for diverse global audiences:

Conclusion

Implementing automatic light and dark themes is a crucial step towards creating a more accessible and user-friendly web experience for a global audience. By leveraging CSS media queries and custom properties, you can easily adapt your website's appearance to match user preferences, reduce eye strain, and improve accessibility for users with visual impairments. Remember to consider cultural associations, accessibility guidelines, and performance considerations to ensure a seamless and inclusive browsing experience for everyone.

By adopting these techniques, you demonstrate a commitment to modern web design principles and cater to the diverse needs of your international audience, making your website a welcoming and comfortable space for all.