If you would like to support CSSPortal, please consider making a small donation.
☕ Buy a CoffeeDark mode has become a popular feature in web design, providing users with a more comfortable browsing experience in low-light environments and reducing eye strain. In this tutorial, we will walk you through the process of implementing a dark mode using CSS.
Basic understanding of HTML and CSS is required for this tutorial.
Create an HTML file (e.g., index.html
) and set up the basic structure:
<!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">
<title>Dark Mode Tutorial</title>
</head>
<body>
<header>
<h1>Dark Mode Tutorial</h1>
<button id="dark-mode-toggle">Toggle Dark Mode</button>
</header>
<main>
<!-- Your content goes here -->
</main>
<footer>
<!-- Footer content goes here -->
</footer>
<script src="script.js"></script>
</body>
</html>
Create a CSS file (e.g., styles.css
) and define your default styles, including the styles for the light mode:
body {
font-family: Arial, sans-serif;
background-color: #ffffff;
color: #333333;
transition: background-color 0.3s, color 0.3s;
}
header {
background-color: #f2f2f2;
padding: 1rem;
display: flex;
justify-content: space-between;
align-items: center;
}
button {
background-color: #007bff;
color: #ffffff;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
}
Add the dark mode styles to your styles.css
file. You can use a media query to apply these styles when the user has enabled dark mode:
/* Dark mode styles */
body.dark-mode {
background-color: #333333;
color: #ffffff;
}
body.dark-mode header {
background-color: #1a1a1a;
}
body.dark-mode button {
background-color: #17a2b8;
}
Create a JavaScript file (e.g., script.js
) to handle the dark mode toggle functionality:
const darkModeToggle = document.getElementById('dark-mode-toggle');
const body = document.body;
darkModeToggle.addEventListener('click', () => {
body.classList.toggle('dark-mode');
});
Finally, link your JavaScript file at the bottom of your HTML body:
<script src="script.js"></script>
Congratulations! You've successfully implemented dark mode using CSS in your web project. Users can now toggle between light and dark modes, providing a more versatile and user-friendly browsing experience.
Feel free to further customize your dark mode styles and expand this tutorial to include more elements and features in your web application.