Member-only story

Sharing a Variable Across HTML, CSS, and JavaScript

Nhan Nguyen
3 min readJan 13, 2025

--

When building modern web applications, having a single source of truth for variables used in HTML, CSS, and JavaScript is often helpful. A typical example is a theme color or font size you want to reference and modify across your styles and scripts. This post will explore how to achieve this seamlessly using CSS custom properties (variables).

Why Share Variables?

Sharing variables across HTML, CSS, and JavaScript offers several advantages:

▪️Consistency: Ensures that the exact value is applied everywhere.

▪️Dynamic Updates: Enables easy updates and live changes through JavaScript.

▪️Simplified Maintenance: Reduces redundancy and keeps your code DRY (Don’t Repeat Yourself).

Step 1: Declare the Variable in CSS

CSS custom properties (variables) start with a prefix and are defined in a selector, typically :root for global scope.

:root {
--main-color: #3498db;
--font-size: 16px;
}

These variables are now globally accessible in your CSS and can be modified dynamically via JavaScript.

Step 2: Use the Variable in CSS

You can use the var() function to reference the custom property in your CSS rules:

body {
color: var(--main-color);
font-size: var(--font-size);
}

--

--

Nhan Nguyen
Nhan Nguyen

No responses yet