CSS relative colors

Back

Common verbose color patterns using CSS Custom Properties

Pretty wastefull and verbose use of CSS Custom Properties for colors.

:root ❴
    // Named based colors
    --clr-primary: #0362fc; // Base color blue
    --clr-primary-dark: #004eff; // Darker, based on blue
    --clr-primary-hover: #a8e3ff; // Lighter, based on blue
    
    // ... or even shades
    --clr-primary-700: #004eff; // Shade based on blue
    --clr-primary-500: #0092ff; // Shade based on blue
    --clr-primary-200: #a8e3ff; // Shade based on blue
❵                  
            

Demo using CSS relative colors

Changing colors relatively, like background-color and box-shadow, based on a base color using CSS Custom Properties .

.status-grid
Default text block.
Info! Your operation was completed.
Warning: Check your input values.
Error: Something went wrong.

How it works

Getting a new relative color using HSL and a CSS Custom Properties hsl(from var(--item-color) h s l) and changing the h (hue), s (saturation) and l (lightness), and optional opacity / 0.5, values relatively based on the from 's CSS Custom Property.

// Parent element
.status-grid ❴
    --clr-base: #212121; // Dark gray
    --clr-status-info: #0362fc; // Blue    
    --clr-status-warning: rgb(200, 100, 0); // Orange
    --clr-status-error: hsl(0 100% 50%); // Red
❵

// Child element
.status-grid__item ❴
    --item-color: var(--clr-base);
    
    // ... now you can tinker with these h s l values relatively
    color: hsl(from var(--item-color) h s l);

    // .. take the `lightness` value from `--item-color` and set it to 85%
    background-color: hsl(from var(--item-color) h s 85%);

    // ... set a relative opacity to 50%
    box-shadow: 0 10px 8px hsl(from var(--item-color) h s l / 0.5);


    // Change the `--item-color` based on status
    &[data-status="info"] ❴
        --item-color: var(--clr-status-info); // Blue
    ❵

    &[data-status="warning"] ❴
        --item-color: var(--clr-status-warning); // Orange
    ❵

    &[data-status="error"] ❴
        --item-color: var(--clr-status-error); // Red
    ❵
❵
            

More demo's and documentation

Awesome demo by Kevin Powell