Create a Dark Mode Theme in Your Web App Using CSS Media Query

Will Mendes
InstructorWill Mendes

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

CSS Media queries are heavily used across web pages for different reasons, such as make your web pages responsive, but what if we can use them to improve web accessibility as well?

In this video, I’m sharing How to use CSS Media Queries for web accessibility in your web app, combining the user preferences choice with prefers-color-scheme media query and enabling dark mode in your web app.

Will Mendes: [0:00] We can open our terminal and create a folder called css-media-queries using the command called mkdir. After that, we can open the folder using VS Code.

[0:13] We can create the files for the project. Let's first create our HTML and link our style sheet file and our code sample. We can add a paragraph and a title so we can make sure the page is working as expected. After that, we can create the link for our style sheet. Let's create a new file called style.css. This file will have all the style sheet for our page.

[0:44] To see them in [inaudible] action, we can go to our CSS file. First, we need to add the first style for light mode. With that, we can add HTML. Background would be white, and a color there will be grey. By default, the page would have those styles.

[1:03] Now we can add @media and create media query using prefers-color-scheme. This makes our app to respect the user choice for the system theme and case it's using light or dark theme. Let's create the CSS rules for dark mode. Once dark mode, the background would be grey, and the color will be white.

[1:28] We can see the CSS Media Query in action by opening the general settings in your device and changing the theme between dark and light mode. Our HTML page should change between the background white and background grey and the color white and the color grey.