Dark mode is a popular feature that can improve user experience by offering a visually relaxing alternative to the traditional bright, white interfaces. Implementing dark mode on your website can be relatively straightforward with CSS. Here's a basic guide to help you get started.

Prerequisites

- Basic understanding of HTML and CSS
- A text editor (e.g., Visual Studio Code, Sublime Text)
- A web browser for testing

Step 1: Create Your HTML File


First, let's create a simple HTML file with some content. Save this file as `index.html`.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Dark Mode Example</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <div class="container">
    <h1>Welcome to My Website</h1>
    <p>This is a sample paragraph.</p>
    <button id="toggle-button">Toggle Dark Mode</button>
  </div>
</body>
</html>{codeBox}


Step 2: Create Your CSS File


Next, create a CSS file and save it as `styles.css`. This file will contain the styles for both light and dark modes.

Light Mode (Default)



/* Light mode styles */
body {
  background-color: #ffffff;
  color: #000000;
}

.container {
  max-width: 800px;
  margin: auto;
  padding: 20px;
}{codeBox}

Dark Mode


We'll use a CSS class to toggle dark mode.


/* Dark mode styles */
body.dark-mode {
  background-color: #121212;
  color: #ffffff;
}{codeBox}

Step 3: Add JavaScript to Toggle Dark Mode


Now, let's add some JavaScript to toggle between light and dark modes. Add the following script before the closing `</body>` tag in your `index.html`.


<script>
  const toggleButton = document.getElementById('toggle-button');

  toggleButton.addEventListener('click', function() {
    document.body.classList.toggle('dark-mode');
  });
</script>{codeBox}

This script listens for a click event on the "Toggle Dark Mode" button and toggles the `dark-mode` class on the `<body>` element.

Step 4: Test Your Website


Open `index.html` in your web browser and click the "Toggle Dark Mode" button. The background and text colors should switch between light and dark modes.

Optional: Save User Preference


You can use `localStorage` to remember the user's preference and apply it when they revisit your website.

Add this script to your `index.html`:


<script>
  // Check for saved user preference and apply it
  if (localStorage.getItem('dark-mode') === 'enabled') {
    document.body.classList.add('dark-mode');
  }

  // Toggle and save user preference
  toggleButton.addEventListener('click', function() {
    document.body.classList.toggle('dark-mode');
    localStorage.setItem('dark-mode', document.body.classList.contains('dark-mode') ? 'enabled' : 'disabled');
  });
</script>{codeBox}



Congratulations! You've successfully implemented a basic dark mode feature on your website using CSS and JavaScript. You can expand on this by adding transitions, optimizing for different devices, or even using CSS variables for more complex themes.