Skip to content

CSS Variable Notes

Thinking through how to best organize CSS variables for site theming.

One variable name set, definition scope changed ✅

  • 👍 Reduces selector code since needn't write two selectors!
  • 👍 Simplifies variable value setting as don't need to append or prepend "dark" or "light" ....
body[data-theme="light"] h1 {
  color: var(--h1-color);
}
body[data-md-color-scheme="default"] {
  --h1-color: black;
}
body[data-md-color-scheme="slate"] {
  --h1-color: white;
}

New variable names set for each variant ❌

  • 🔻 Biggest annoyance of this method is the need to actually create multiple selectors for the differences in variables
  • Requires the need to continue making sure variants like "dark" are properly added
  • This total number of variables remains the same as media query method since media query method just wraps "dark" values in a media query
    body[data-theme="light"] h1 {
      color: var(--h1-color);
    }
    body[data-theme="dark"] h1 {
      color: var(--h1-color-dark);
    }
    :root {
    --h1-color: black;
    --h1-color-dark: white;
    }
    

Prepend

Easier to see all vars grouped ...

--content-bg: #FFFFFF;
--content-dark-bg: #1E1E1E;

Append

Might be easier when placing vars next to each other is important ...

--content-bg: #FFFFFF;
--content-bg-dark: #1E1E1E;

Variables inside variables ❌

  • Another idea for getting vars near each other - nmore here .. https://chatgpt.com/c/56fc5927-bb1d-4a45-87e9-64511b8aaf10
    /* Grouped Variables */
    :root {
      --sidebar-bg-light: #ffffff;
      --sidebar-bg-dark: #262626;
    }
    
    /* Apply based on theme */
    :root {
      --sidebar-bg: var(--sidebar-bg-light);
      --content-bg: var(--content-bg-light);
      --header-bg: var(--header-bg-light);
    }
    
    @media (prefers-color-scheme: dark) {
      :root {
        --sidebar-bg: var(--sidebar-bg-dark);
        --content-bg: var(--content-bg-dark);
        --header-bg: var(--header-bg-dark);
      }
    }