Drop in dark mode with 2 lines of code with prefers-color-scheme
and no flash of unstyled content (FOUC)!
Warning
This project is a WIP, and should not be used in a production environment yet.
CDN link to be used in your project
<script src="
https://cdn.jsdelivr.net/npm/[email protected]/src/theme-toggle.min.js
"></script>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css" />
<script src="
https://cdn.jsdelivr.net/npm/[email protected]/src/theme-toggle.min.js
"></script>
</head>
<body>
<button id="theme-btn">Toggle Theme</button>
</body>
</html>
styles.css
:root,
html[data-theme='light'] {
background-color: white;
color: black;
}
html[data-theme='dark'] {
background-color: black;
color: white;
}
Astro Set Up
src/pages/index.astro
---
import '../styles/globals.css'
---
<html lang="en">
<head>
<script is:inline src="
https://cdn.jsdelivr.net/npm/[email protected]/src/theme-toggle.min.js
"></script>
</head>
<body>
<button id="theme-btn">Toggle Theme</button>
</body>
</html>
src/styles/globals.css
:root,
html[data-theme='light'] {
background-color: white;
color: black;
}
html[data-theme='dark'] {
background-color: black;
color: white;
}