Ronalds Vilciņš

The light-dark() CSS Function



The light-dark() CSS function offers a straightforward way to create websites that seamlessly adapt to user-preferred color schemes, such as light or dark mode. By defining just two color values, you can ensure your site remains visually appealing, no matter the user’s theme preference.

How Does It Work?

  1. Detecting User Preferences:
    The browser identifies the user’s preferred color scheme based on their system or browser settings.
  2. Color Matching:
    The light-dark() function selects the appropriate color from the two values you provide—one for light mode and one for dark mode.
  3. Dynamic Styling:
    The website automatically adjusts its colors to align with the user’s preferred theme.

Syntax Overview

The syntax for using light-dark() is clean and intuitive:

color: light-dark(light-color, dark-color);

Example Usage

body {
  background-color: light-dark(#f0f0f0, #222); /* Light: #f0f0f0, Dark: #222 */
  color: light-dark(#333, #fff);               /* Light: #333, Dark: #fff */
}

Why Use light-dark()?



0  0  0

Comments

Reply on Bluesky here to join the conversation.