Use Media Queries to Adapt to a User's Preferred Color Scheme

Kayla Sween
InstructorKayla Sween
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

Kayla shows how to use the prefers-color-scheme media query in CSS to use system preferences to determine whether we need to display a website in light mode or in dark mode. This lesson starts in light mode and adds additional styles for dark mode (prefers-color-scheme: dark). However, this also applies when going from dark mode to light mode (prefers-color-scheme: light). The example only uses HTML and CSS, but you can use whatever front-end development method or framework you want as long as you can write media queries.

The first thing to do is to add the prefers-color-scheme media query for the color scheme you're responding to. Then, add CSS selectors for the corresponding HTML elements that need to change colors to your media query section. In this example, the elements that needed to change colors were the body, anchor tags, active navigation list item, and button.

Kayla Sween: [0:00] The first thing I'm going to do is add the media query prefers-color-scheme, dark. Then, I'm going to add the body styles that I want to change for dark mode. I want to change the background color, which I'll change to this dark gray. Then, I'll change the text color to this light blue. After saving, we can see that our background color is the dark gray and our text color is that light blue.

[0:20] The next thing we need to add our new anchor tag styles, so that we have sufficient contrast between our anchor tags and our background. I'm going to make our anchor tags light pink. Then, I'm going to change the active style for our nav items to the same pink color.

[0:32] Now, everything on our home page looks pretty good. If we move over to the Contact page, I'm going to change the submit button to stand out a little bit more against the gray background. I'll change the background color to the same pink color as our links and our text color to the same gray as the background.

[0:45] Now, if you go into the system's preferences on your computer, and toggle between light mode and dark mode, you'll see that your website will change colors as well.

cognivore
cognivore
~ 2 years ago

TIL!

Markdown supported.
Become a member to join the discussionEnroll Today