Adding a dark mode feature to your website can improve the user experience and allow users to view your site in a darker color scheme. In this blog post, I will show you a simple method to implement dark mode using CSS.
To get started, you can use the following lines of CSS code:
@media (prefers-color-scheme: dark) {
body {
filter: invert(100%);
background-color: rgb(29, 32, 31) !important;
}
img,
.astro-code,
.emoji,
iframe /* for recaptcha */ {
filter: invert(100%) !important;
}
}
This CSS code utilizes the @media
rule to target devices that have dark mode enabled. The prefers-color-scheme: dark
media feature is used to detect if the user has set their device to use a dark color scheme. We then apply the necessary CSS rules to style our website accordingly.
In the code above, body
represents the overall content of your website. By using the filter
property with the invert(100%)
value, we can invert the colors and achieve the dark mode effect. The background-color
property sets the background color of the page to a specific shade of dark gray.
Additionally, we apply the same filter
property to img
, .astro-code
, .emoji
, and iframe
. These selectors target specific elements that should also be inverted to maintain consistency with the overall dark mode theme.
Once you have added this CSS code to your website, users who have enabled dark mode will see your website with a dark background and inverted colors. Users who don’t have dark mode enabled will see your site as usual.
That’s it! You have successfully implemented a simple dark mode feature on your website using CSS.
Tags: dark mode, CSS styling, web development