295 Theme Aware Styling

Theme-Aware Styling

The Problem

When working with a themed front-end framework (like Hugo with a light/dark mode theme), hardcoding specific color values (e.g., background-color: #FFFFFF;) in custom CSS can lead to visual inconsistencies. These hardcoded values will override the theme’s intended colors, causing elements to look out of place when the theme is changed (e.g., a bright white box appearing in dark mode).

The Solution

The correct approach is to leverage the theme’s existing CSS variables. Instead of hardcoding colors, use the variables provided by the theme.

Example

Incorrect (Hardcoded):

.my-custom-box {
  background-color: #FFFFFF;
  border: 1px solid #CCCCCC;
  color: #000000;
}

Correct (Using Theme Variables):

.my-custom-box {
  background-color: var(--BOX-BG-color);
  border: 1px solid var(--border-color);
  color: var(--MAIN-TEXT-color);
}

By using the theme’s variables, our custom components will automatically adapt to the current theme, ensuring a consistent and professional look across all modes.

How to Discover Variables

The best way to discover available CSS variables is to use the browser’s developer tools. Inspect a well-styled element on the page and look at the “Styles” or “Computed” pane to see which variables are being used. This is the most reliable method for grounding our styles in the site’s actual theme.