Syntax Video
Modern CSS Theming | Light Mode / Dark Mode and More!
- 0:00 intro
- 0:27 color-scheme
- 1:57 picture source media
- 3:22 light-dark
- 5:07 css only theme switcher
- 8:32 save user theme preference to localStorage
- 12:13 set picture source with selected theme
- 14:55 matchMedia prefers-color-scheme
- 19:08 next-themes package
- 19:44 set the data-theme attribute on page load
- 22:54 avoid prefers-color-scheme dark
- 24:39 syntax 891
- 24:56 color-mix color palettes
- 26:15 relative colors
- 27:49 thanks!
intro
What's up? CJ here. In this video, I want to show you some modern CSS features we can use to get dark mode and light mode in a theming system on our website. I'll also show you how to create a CSSonly theme switcher. And then I'll show you how we can incorporate JavaScript to save a user's preferred theme to local storage. I'll also show you how we can tap into what the user system theme is and react whenever that changes and a whole lot more. So, let's dive in. So, I have this simple example here. We just have some text elements but also some form inputs and scrollable areas. So we can see how the CSS actually affects these by default. Now the first property you should know about is called color scheme. And this CSS property is baseline widely available. It's been available since February 2022 and has over 95% browser support. So you can definitely use this when you're building modern websites. And it's as simple as this. So we're going to use our root selector here and we're going to set the color scheme to light dark. And what
color-scheme
this says is our website supports both the system light theme and the system dark theme. And just like that, if we head back to our website, we instantly have dark mode. And that's because I have my system color preference set to dark. So here on a Mac, you can head to system settings and appearance. And if I change it to light, the page automatically updates. And for this example, this is literally all the CSS I have. I don't have any extra JavaScript changing the styles or anything like that. With this one simple property, you can use the default styles supported by web browsers to automatically get light and dark mode. Now, the other thing to take note of here is how the browser styles things like scroll bars and text inputs when you use that color scheme property. Right? If I switch back to light mode, you'll see that the inputs are white and changes the color of the scroll bars. But when we're in dark mode, we automatically get those styles.
So, even as you start to further customize your dark and light themes, you definitely want to use that color scheme property because it's going to add some default styles to elements that you might not otherwise style with your own theme. Now, another thing we can do that's completely built in is automatically change this image depending on the user's preferred color scheme. So, there is this picture element that's been baseline widely available since 2016 and it can accept a source element within it that specifies a media query. So we can combine this with the prefers color scheme media query which is baseline available since 2020 and then pass in a prefers color scheme dark. So we could automatically swap this image out for an image that looks better whenever we're in dark mode. Now the prefers color scheme media query has over 96% support. So this is definitely something you can use. And for this example I'm using React. And by default I was just loading in that dark logo. But if we pull in the picture element, we can have a source specify what the URL should be and then specify
picture source media
a media query for when that specific URL should be used. So by default, it's going to use this black text logo. But if we're in dark mode, it will use this white text logo. So if I save this and head back to the site, now we have this nice logo that matches the scheme of the site. And this media query automatically reacts to the system settings. So if I change to light mode, you can see that image swaps out for one with black text.
And if I switch back to dark mode, it swaps to the one with light text. So picture with source element in a media query is really great. There is one caveat. This will not work in some scenarios, especially if you have a custom theming system. So I'll show you how we can manage that once we implement a theme switcher. Now this next CSS function we can use is called light dark. It's more recently available. It's baseline 2024 and currently only has about 87% browser support. But if you're only supporting modern web browsers, you can definitely take advantage of this.
light-dark
And the way this works is you can specify a color to use when the color scheme is light and then another color to use when the color scheme is dark. So instead of just using the browser's default dark and light colors, let's say we have a dark color that's just going to be dark slate gray, which is built into the web browser. And then we also have a light color. Let's say it's beige, like so. And then we can specify a foreground and a background variable.
So let's say we have FG and then we'll use light dark. So when we are in light mode, our foreground, the text color in this case will be our dark variable. And then when we're in dark mode, the foreground will be that beige color. So we'll grab that light variable. And then we can do the same thing with the background, but just swap them out. So when we're in light mode, let's make the background beige. And when we're in dark mode, we'll make the background that dark slate gray. And now that we have all of these variables, we can apply them. And so we'll set color equal to the foreground and the background equal to the BG variable. And so now when we're in light mode, we'll have a beige background with dark slate gray foreground. And when we're in dark mode, we'll have a dark slate gray background with a beige foreground. Now, when you're implementing a theming system, it's usually slightly more complex than just swapping out your foreground and background colors. This is a very simple example, but with these changes here, now when we head to the site, we get a
slightly more interesting theme. And if we switch to light mode, we can see the colors automatically swap. Now, using the system color mode like this is a good base default, right? Because typically users are going to set their preference to dark or light mode at the system level, and now your website is responding to that. But sometimes people want to change the theme of your website and maybe even if they have dark mode set on their operating system, they still might want to set light mode on your specific website. Depending on what kind of website it is, maybe like they like to read in light mode. So you should give them this ability to change the theme. So let's create a simple theme switcher. And I am inside of React, but this will work with just regular HTML as well. So I'm just going to have a simple select statement. And first we're not going to have any JavaScript. We're going to do this purely with CSS. So let's add an option for the system theme. We'll add an option for the light theme. And then we'll add an option for the dark theme.
css only theme switcher
So that gives us this drop down here. But when they choose light, we should force the light theme on the website. And when they choose dark, we should force the dark theme on the website. Now to do this purely with CSS, we need to know which one of these options is selected. So for that, I'm going to give each one of these an ID. I'm going to call this theme system. We'll call this one theme light. and this one theme dart. Now using these ids we can create some CSS selectors. So if we head back to our CSS first off I want to know if the theme system option is selected. So we'll select from the root element and then we can use the has selector. So this says select the root element if it has this specific selector that I'm specifying in here. And in this case I want to find the option whose ID is theme-system. And I want to find that option if it is selected. And the way you do that with CSS is you use the checked property. And even though this is a select box, it's not a check box.
The checked property says that this specific option is selected. And what we'll say is when that one is checked, we actually want to set the color scheme to light dark like so. And then we can duplicate this for all of the other options. So we'll say when the root has an option whose ID is theme light and it is checked, force the color scheme to light. And then we'll do the exact same thing with dark. So when it has an option whose theme is dark, force the color theme to dark. And just like that, we should have a nice little theme selector. And you can see even though my system setting is still set to dark, we actually are allowing the user to change it to dark or light. And also giving them the option to go back to their system setting. This is the one thing that a lot of websites forget is maybe the user does want to go back and depend on their system settings. So if we choose system now, it will still react if they change their color at the system level. And so I think it's always important to include that option there because again, they may not want to always have light mode or always have
dark mode. Now, because we're only using CSS for this, we haven't written a single line of JavaScript. When I refresh the page, it's not going to save the theme setting that they set there. And the only way you'll be able to save this is with JavaScript. And that leads us also to our other problem. You can also see that even though I'm changing to light mode, that picture element is not respecting the fact that the root document specifically has the color schema set to light mode. It's still only looking at the system setting to swap this out because you can see here if we head back and change this, this does swap the image. Uh but that's not exactly what we want. So let's actually implement a simple theming system so that way we can tap into JavaScript to know that we need to change that element. Now, the way we can save the theme, which is what the user has selected here, is by putting it in local storage. You could also use session storage or try storing it in a cookie.
save user theme preference to localStorage
Local storage is going to be the easiest way. Like I said, this is going to require some JavaScript. So, I'm actually going to extract out this select element into its own component. I'm going to call it theme select and then export a function. And then we'll import this component back in the app. So here I'll have the theme select and that should behave exactly as before but now it's in its own file and I can give it some nice JavaScript codes. So essentially what we want to do is we want to listen for when this changes and when it changes write that theme value to local storage. So for this we're going to need some state. We'll call this theme and we'll default it to the system theme. Now, u stateate comes from React. And I actually want to be able to use some TypeScript here. So, we have some nice type completion. And I'm going to create a TypeScript type called theme. And this is just going to be a type union that gives us system dark or light. And then we can pass that type in here to use state. And now whenever I'm setting the state, I'm going to get some nice type completion of these specific theme values. So, first we'll tap into
the current value. And so, here we'll say the value of the select is the current value of that theme state variable. And then we need to tap into when this select changes. And here this is going to give us the event. And we just want to set the theme with event.target. And the value here is a string. So we do want to set the value for each of these options so that it aligns with our theme system here. So system dark or light. So for each of these I need to say that the value is system, the value is light and the value is dark. And this way whenever our change handler runs this these specific values are going to be what's passed in as e.target value. Now that's still just a string according to typescript. So we can use a type assertion here that says hey we know that that's going to be of type theme. So now I'm keeping track of this state. When the page loads it's going to be system. Whenever they change the drop down it's going to update our state variable here. And so now we can just listen for when this state variable changes and then write that value to
local storage. So I'm going to use a use effect for this. and use effect accepts a callback function and a dependency array. So we're going to say we're dependent on that theme variable and whenever that changes we want to write the value to local storage. So here I'll just say local storage set item. We'll just call it theme and then we'll set the value to be the current value of theme. So now every time we change the drop down it's going to write it to local storage. So let's see this in action. So now if I change this we should see that value pop up in local storage. So if I change this to light we see theme is set to light. If I change this to dark, we see theme is set to dark. Now that's putting it in local storage, but we're still not reading from it. If I refresh the page, you can see that it resets back to system. Now when the page loads, we actually want to read from local storage so we can get the value that we saved. And we'll do that with the initial value here on use state. So we will say local storage.get item and say we want the theme. But as you can see, that could be null because if they're visiting our site for the first time, there won't be anything in local storage. So we'll say grab that
value or if there's nothing in there, set it to theme. Now we have the same type issue here. Whenever you pull something out of local storage, it's just a string. So we can use a type assertion that says, hey, I know that that's going to be of type theme. And just like that, we should have the ability to save our theme. So if we change to light mode and then I refresh the page, look at that. We instantly get light mode. So this is looking great. A user can, for instance, set the site to light mode even though the system setting is set to dark. And similarly, their system setting could be set to light, but they could choose dark mode.
And when they come back to the site, it will respect that setting. Now, in order to get this picture working and changing with the theme, we will have to tap into what the current theme value is as well. Now, in order for this logo component to get access to what the current theme is, we need to lift that state up. There's a lot of ways to do this. Typically in a larger application, you might actually use the context API or some other state management library. But for our purposes, we're actually just going to grab this effect and the state and pull it up to the app. And so that way we can use it inside of our other components.
set picture source with selected theme
So I'm going to pull this out of here, specify it in the app. We'll also pull our type out, pull it into a common spot, just call it types. And then this component is now going to need the theme value and the set theme function. So we can define our props theme. We'll come in and this is of type theme. We'll import that in from our types. And then we also need set theme and we'll grab that type on the other side. So let's import use state and use effect and theme and all the other things that we need. And if you hover over set theme, you can see that this is a react dispatch react set action of theme. So we can copy that type and set that is what the type will be there. And then also dstructure set theme. So now theme select is happy. It's going to get passed down a theme and a set theme and it will work as before. But now we defined that state in the parent component and we can pass it down. So we'll pass down the current theme and we'll pass down set theme. So our app should behave exactly as before. I can
still switch between dark mode and light mode. But now that we've moved that state up to the app, I can also pass it down to the logo component. So if the logo component accepts the theme, we can now take that into account when deciding which of the sources to show. So if we head to our logo component, we'll grab the theme which is of type theme. We'll import that type. And now we can use that theme here. Now unfortunately we can't depend on this media query anymore because this only pays attention to the system theme, not any custom theme that we've set. So what we're going to do is just have a conditional that says if the theme is equal to dark, then match this for everything. Otherwise, match this for nothing. And so if the theme is set to dark, it's going to automatically swap to this source. But if the theme is set to anything else, it's going to just show the default source. And just like that, our image should now be showing the correct image based on dark or light mode. But there's one more issue we need to worry about. What if they are in
system theme mode and their system theme is set to dark? Well, that does not work with our current logic because our theme is either system light or dark. And so for this we actually need to take into account what is the user system color preference. And for this we can use match media which is built into JavaScript in the web browser. And this has been baseline since 2015. So you can use this absolutely everywhere. And essentially we can pass in a media query and then react to when that media query changes and also give what the latest value is. So I'm actually just going to do this at the top level of my app here.
matchMedia prefers-color-scheme
I'll call this prefers dark and we can say match media and then pass in a media query. So our media query here is this prefers color scheme dark and so this variable here has a few values inside of it and we can say does it matches and if it does match then that will be set to true and we know that the user's preferred theme is dark. So for this I'm going to have one more state variable so I can use it throughout my app and I'm going to call this the color preference.
We'll have our setter and this will be a state variable that says what the user prefers. Do they prefer light mode or dark mode and so the initial value here will be if prefers dark matches then I want to set this to dark otherwise their preference will default to light. And we can also have some type safety here. So if I type this I can say it's a theme but it's a theme that is only dark or light. So built into Typescript is this omit function. So we can say grab the theme and omit system. And so now color preference can only be dark or light.
Now one of the other nice things about match media is we can actually listen for changes. So if a user is actually toggling their preferred appearance at the system level, we can know about that on our web page. And so for this I'm going to use a use effect. And I just want this to run once when the component mounts. So I'll pass in an empty array.
So inside of here, if I say prefers dark addevent listener, we can specifically listen for the change event. And then this event will be a media query list. So inside of here, we can then say set color preference with E dot matches. And so we'll do the similar logic. So if this matches, then that means we want to set it to dark. Otherwise, we want to set it to light. Now there's one issue.
Now, there's one issue with just doing this and not removing the event listener because this will potentially add multiple event listeners and if this use effect ever reruns, we want to remove the previous ones because we don't have a memory leak with lots of change event listeners. So, first of all, let's just type this. So, this is a media query list event. So, we'll say E is a media query list event. And then I can extract this out into a variable. We'll call it handler. So, here I have my handler looks like so. But then a use effect can return a function. And that function is essentially our cleanup function. It'll get called whenever this use effect needs to run again. So if I return a function that removes the event listener, this will make sure that we don't have that memory leak. So here we'll remove that event listener or change and pass in that handler. And so now I have this nice reactive color preference variable. So when the page loads, we'll know what their system color preference is. But if they ever change their system color preference, that's going to update our state variable to always have the latest system color preference. And so now our
picture component can also take that into account. So it can take in the theme and it can take in the color preference and if the color preference is dark, it knows that it needs to show that specific image source. So if we head back to the logo, this is also going to take in the color preference. Color preference is of type omit system from theme. So now we can take into account the color preference. And essentially what we need to do is if theme is set to system then use the color preference. But if theme is set to dark or light then use the theme. So I'll have a variable here. We'll just call it is dark. We'll say if the theme is equal to system and the color preference is equal to dark then we know that we're in dark mode for the system theme. Or if the theme is dark. And so now we can use this is dark variable instead of just checking if the theme is dark. And so now this allows the user to set their theme but still show the correct image even if that's not their
color preference at the system level. So now in light mode you can see that image. In dark mode you can see that image. And if we're in the system color mode and I change between light and dark we can see the the image swap out. Now, if you are going to be implementing this in your React app, I actually recommend that you don't implement it from scratch because if you want this to better work throughout your application, you probably would add the context API or some state management library. But there is this package called Next themes. And this works inside of React, not just Next.js. And it essentially gives you a provider and a hook you can use to determine what is the current theme and also a setter to set that theme. So, this hides all of that logic for querying for the color preference or storing it in local storage. All of that's hidden behind this library. So, I highly recommend if you're building a React app, you should use this library.
next-themes package
set the data-theme attribute on page load
Now, there's one other thing we need to fix. So, let's say my preferred system color mode is light, but on the site I want my color preference to be dark. Watch what happens when I refresh the site. Pay close attention. Flashes. because by default that code that sets the theme doesn't kick in until all of this JavaScript has run. And so you're going to get that flash just like that.
And so if I want to prevent that flash, I essentially need to make sure that the theme is set before anything else even loads. Now the way I'm going to do this first is by updating our CSS. Now this CSS only way of changing the theme is great, but typically we also want to tap into a data- theme property on some root level element. So let's also do that.
Let's say if the root element has the data- theme property set to system, set the color scheme to light dark. If they have data theme set to light, set the color scheme to light. And if they have a attribute called data theme that's set to dark, set the color scheme to dark.
So now that we're using this selector before the rest of the page loads, we can actually set this data- theme attribute on our top level element. And that will make sure that we don't see that flash of color. And we can do this. Specifically, I'm in a V app, but I'm just going to do it in my index.html here. And I'm going to write a very simple script tag that's in the head that loads before anything else. And inside of here, we can grab the HTML element. So, I'm just going to query for that HTML element. And then, if it exists, we're going to set the attribute data- theme to be the current theme value. And we can just grab that from local storage. So, I can say local storage.get item theme. And if that doesn't exist, like this is the first time they're visiting the site or they haven't changed the dropdown, then we'll default to system. Now, let's see this in action. If I open up the dev tools, you can now see that when the page loads, our HTML element has this data- theme attribute on it, but we're still going to get that flash of color because I'm using Vit. And in dev mode, Vit
actually inserts several scripts at the top of the head. So, when we're in dev mode, this is not going to be the first script that runs. But if we build the application and then preview it, that will be the very first bit of code that runs. So this is always going to run before any of my CSS loads, any of my other JavaScript. And because it runs before the rest of that, we don't see that flash of color. And if we open up the dev tools, we can see that that data- theme dark is still getting set.
And we can refresh all day long, and it doesn't flash the color. Now, because we're now setting that data- theme attribute, you'll notice that it doesn't update when I change this dropown. And that's because we haven't written the code to do that. And really that code just needs to happen right here. So just like we're writing the theme to local storage whenever the theme changes, we should set the data theme attribute on the HTML element whenever the theme changes as well. So we can grab that HTML element and then set the data- theme attribute to be the theme value there. And so now when we change that dropown, it's also going to set that data- theme property on the HTML. So if I switch to dark mode, you'll see that that automatically updates. So if you have any other code that's dependent on that attribute value, that's always going to have the latest value there.
avoid prefers-color-scheme dark
Now, when you're creating your theme this way, another thing you need to take into account is media queries. So just like we have this media matcher here for dark mode, you probably have written some CSS that says when they prefer the dark color scheme, we'll specify our styles here. But look what happens. So, I'm going to say we're just going to override the color to be yellow and the background to be red when the user prefers the color scheme dark. And currently my system preference is set to dark. And now when I go to the web page, we see that. But if I try to change my theme to light or dark, you'll see the only thing that's actually changing are those system elements. It's always using color yellow and background red because my current system preference is dark.
Um, and if we change to light mode, this media query is not going to match anymore. And now our our site should behave as it did before. But that's one thing you need to take into account. And essentially, if you've implemented this theming system, you should not use this media query like this anymore. You should just specify your styles inside of this matcher here. So if I want styles that are specific to dark mode, I am just going to specify them in this selector here. And then we can also use nested selectors. So if I want to change the way buttons look when I'm in dark mode, I can select them here and now it will apply when the user has either the system color preference of dark or they've chosen dark mode. So once you start implementing your themes this way, you do want to make sure you remove any media queries like this because they're only looking at the user's color preference. They're not looking at your theme preference. And now with this change, that ugly yellow and red should only happen if I'm in dark mode. But if I'm in light mode, it still respects the colors that were set. Now, there's a ton
syntax 891
more we could cover here. I highly recommend you check out episode 891 of syntax. Scott and Wes talk about a bunch of other CSS properties you can use like color mix and contrast color that's coming. Scott also shares some snippets of how he likes to set this up. So, definitely check out that episode. Specifically, if you're looking at color mix, you can do some really cool stuff.
color-mix color palettes
So, I'll link this MDN article in the description, but essentially color mix allows you to take two different colors and then mix them together. But you can get some really interesting results like creating color palettes, right? So, we can have a base color of blue and then use color mix to just gradually mix in white and black to create almost like a gradient of colors and then we can use those colors throughout our app as kind of like a color palette. And similarly, if you mix in like white with the color, you can get a more muted version of the color. And this is really great for creating like hover states, right? You can have your default color being this blue, but then when you hover, you get like a slightly lesser blue, and that color was automatically calculated by mixing in white with the blue color.
They also show a really cool example here where you set your default color value. Everything else is based on that color value. And then if you want like a secondary class, you just change the base color because color mix is using that variable. So, when it's a base card, it's using blue with color mix to change it to this light background color, but when it's secondary, it's using deep pink to get that lighter color there. So, color mix is really great. I've only just started to play around with it, but it is really slick.
It's part of baseline 2023 and currently has 92% browser support, so it has pretty good support. And then another one that's really useful for building out themes is relative colors. And you can do some really cool stuff with this, like creating automatic color palettes. So in this MDN article, they actually show this example of creating a color palette generator. So just based off a base color, we can use color math to find complimentary colors or use color theory like triadic and tetratic. So all of these other colors are based on this base color here. You can do things like monochrome. And relative color is super powerful because you can take in a color of any type. So it could be specified as a hex code or RGB. And then you can use any other color function like LCH or HSL. And this relative color function gives you access to the direct LC and H values. So then you can just modify those with some calculations. So I'm not great with color. I'm most familiar with like HSL and RGB because HSL is hue,
relative colors
saturation, and light. And I know that if you change the hue value, you can just get a different color that has the same saturation and light. Um, I guess that's pretty obvious, but that basically allows you to maybe like add or subtract from the current hue value to rotate around the color wheel because the H value is from 0 to 360 and that represents all the colors. I don't know.
Check out relative colors. It's super sweet. Of all of these, relative color definitely has the least support. So, it's part of baseline 2024, but currently only has about 90% support. Once we get better support for this, I'm definitely going to start using across a lot more websites because being able to just directly modify color values like this is is awesome. Okay, that's all I have for you in this video. If you have any questions or comments, leave them down below. If you think I did something wrong, let me know down below. All of the code I wrote will be linked in the description. And uh yeah, I'll see you in the next one.
thanks!
Quote it with credit and a link. Quoting Syntax