DEV Community

Cover image for Add dark mode to your site with this short CSS trick

Add dark mode to your site with this short CSS trick

Gábor Soós on September 10, 2019

Most applications nowadays have dark mode: your command line, your IDE, your browser, etc. Why would your site be any different? Your website can a...
Collapse
 
kylefilegriffin profile image
Kyle Griffin • Edited

What's more likely to happen in this case is that you'll have color set on specific parts of the site for different things. So the better thing to do is to use CSS variables.

CSS Variables example for dark mode

Collapse
 
papaponmx profile image
Jaime Rios

Simple but effective. Thanks for sharing

Just to enrich the conversation I want to add that another consideration is that if you are using styled-components a dark theme might be accomplished with something in a similar way, for example:

const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

const lightTheme = {
    color: 'black',
    backgroundColor: 'white',
};

const darkTheme = {
    color: 'white',
    backgroundColor: 'black',
};

// ...

render() {
    return(
        <ThemeProvider theme={prefersDark ? darkTheme : lightTheme} >
        </ThemeProvider>
    );
}


Collapse
 
amarok24 profile image
Jan Prazak

When I change to dark theme in Firefox then this line:
window.matchMedia("(prefers-color-scheme: dark)").matches
still returns false.

Collapse
 
timjkstrickland profile image
Tim JK Strickland

So so slick. Love it

Collapse
 
197858 profile image
197858

How to change block constanta and let to global scope javascript?

Collapse
 
codevanaco profile image
Codevanaco

Awesome! Good work!

Collapse
 
djsmacker01 profile image
Adewale Adedeji

Mine is not working

Collapse
 
dillionmegida profile image
Dillion Megida

Sorry, how do you activate the dark scheme?

Collapse
 
labilbe profile image
Franck Quintana