Home Projects Portfolio Dashboard Export PDF Log in

Implementing Dark Mode in portafolio-luis-romero

Introduction

I have been working on the portafolio-luis-romero project, a personal portfolio site, to enhance the user experience by adding a native dark mode toggle. Providing a dark theme is no longer just a visual preference; it is a standard accessibility and battery-saving feature for modern web applications.

The Challenge

The primary goal was to create a seamless switch between light and dark color schemes without requiring a page reload or complex backend state management. The challenge lies in ensuring that the styles persist across navigation and respect the user's system preferences.

The Solution

I utilized CSS custom properties (variables) to define the color palette, allowing for easy updates to the theme. By toggling a class on the body element, we can swap the entire application's theme dynamically.

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
}

.dark-mode {
  --bg-color: #1a1a1a;
  --text-color: #f4f4f4;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

Using JavaScript, we detect the click event on a toggle button and persist the user's choice in localStorage:

const toggleBtn = document.querySelector('#theme-toggle');
toggleBtn.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
  const isDark = document.body.classList.contains('dark-mode');
  localStorage.setItem('theme', isDark ? 'dark' : 'light');
});

This approach ensures that the state is retrieved and applied as soon as the DOM content is loaded, preventing any "flicker" of light mode content when the user prefers dark mode.

Key Decisions

  1. CSS Variables - Enables centralized control of the theme colors, making it easier to add new themes in the future.
  2. LocalStorage Persistence - Saves user settings locally, ensuring a consistent experience across sessions.
  3. Class-based Toggling - A clean, performance-oriented way to switch styles using the browser's native rendering engine.

Takeaway

Start your next project by defining your color palette using CSS variables. It makes implementing dark mode a simple task of swapping variable values rather than overriding individual CSS rules across your entire stylesheet.


Generated with Gitvlg.com

Implementing Dark Mode in portafolio-luis-romero
Luis Romero

Luis Romero

Author

Share: