body {\n background-color: white;\n color: black;\n}\n\n\/* Detecting dark mode *\/\n@media (prefers-color-scheme: dark) {\n\n body {\n background-color: black;\n color: white;\n }\n\n}<\/code><\/pre>\n\n\n\nIn the above code, we have some CSS styling for body, background color as white and text color as black. When the dark mode preferences are detected we are switching the styles, background color as black and text color as white.<\/p>\n\n\n\n
This seems straight forward when it comes to monochromatic color. But when it comes brand colors, You have to design your brand accent into it.<\/p>\n\n\n\n
Here is another example. In this example, we will have a card with heading and paragraph changing colors as we change our system preferences.<\/p>\n\n\n\n
If you notice closely, we have two headings and we are hidding them based on the mode.<\/p>\n\n\n\n
<div class=\"card\">\n <h1 class=\"visible dark\">Dark Mode<\/h1>\n <h1 class=\"visible light\">Light Mode<\/h1>\n <p>Take a look at our article on implementing dark mode with css and why you should add it to improve accessability for your users.<\/p>\n <a href=\"\/articles\/adding-darkmode-to-website\/\">Learn more \u00bb<\/a>\n<\/div><\/code><\/pre>\n\n\n\nAdd we have our CSS, here am using CSS variables<\/a> for handling colors.<\/p>\n\n\n\n\/* Default color variables *\/\n:root {\n --bg: #eee;\n --text-color: rgba(0,0,0,0.9);\n --card-bg: #fff;\n --primary-color: blue;\n}\n\n\/* Some styling for the layout *\/\nbody {\n background-color: var(--bg);\n color: var(--text-color);\n display: flex;\n justify-content: center;\n align-items: center;\n height: 100vh;\n}\na {\n color: var(--primary-color);\n text-decoration: none;\n}\n.card {\n margin: 40px 40px;\n padding: 40px;\n line-height: 1.5;\n border-radius: 9px;\n background: var(--card-bg);\n text-align: center;\n max-width: 54ch;\n}\n.card h1 {\n margin-top: 0;\n}\n.visible {\n color: var(--primary-color);\n}\n.light { display: block; }\n.dark { display: none; }\n\n\/* Styling for Dark mode *\/\n@media (prefers-color-scheme: dark) {\n :root {\n --bg: #111;\n --text-color: rgba(255,255,255,0.77);\n --card-bg: #222;\n --primary-color: pink;\n }\n .light { display: none; }\n .dark { display: block; }\n}<\/code><\/pre>\n\n\n\nNow try switching your appearance settings from light to dark mode vice versa.<\/p>\n\n\n\n
\n See the Pen \n Dark mode example for W3Layouts article<\/a> by Hidayath (@w3hidayath<\/a>)\n on CodePen<\/a>.<\/span>\n<\/p>\n