Skip to content
CSS

CSS Variables

Custom properties.

By EZ4Code Team
cssvariables

Code

:root {
    /* Colors */
    --primary: #3498db;
    --secondary: #2ecc71;
    --danger: #e74c3c;
    --text: #333;
    --bg: #fff;

    /* Gap */
    --spacing-sm: 8px;
    --spacing-md: 16px;
    --spacing-lg: 24px;

    /* Fonts */
    --font-size: 16px;
    --font-family: 'Helvetica Neue', sans-serif;

    /* Border radius */
    --radius: 8px;
    --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* Use variables */
.button {
    background-color: var(--primary);
    color: white;
    padding: var(--spacing-sm) var(--spacing-md);
    border-radius: var(--radius);
    font-size: var(--font-size);
    box-shadow: var(--shadow);
}

/* Dynamically modify variables */
.dark-theme {
    --text: #f0f0f0;
    --bg: #1a1a1a;
    --shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
}

/* JS manipulate variables */
// document.documentElement.style.setProperty('--primary', '#e74c3c');

/* Fallback value */
.element {
    color: var(--undefined, #333);
}

Explanation

CSS variables start with --; var() references them; they can be dynamically modified at runtime via JS.

More CSS Snippets