DEV Community

Cover image for Custom Properties, never again without you
Tamer
Tamer

Posted on

Custom Properties, never again without you

Custom properties are one of the most important frontend development innovations in last years, definitely.

Custom properties are CSS Variables that are assigned to the properties and that can dynamically change the value!
The benefits are tangible during development, let's analyze simple examples to highlight the benefits.

CSS, Traditional way

In this portion of the code, with the traditional CSS we must explicitly declare the initial value of the property and that of the status changes.

.block {
  background-color: red;
}

.block:hover {
  background-color: blue;
}
Enter fullscreen mode Exit fullscreen mode

SCSS Variables

With the pre-processors, in the example that follows SCSS, it is possible to be more ordered: by storing the value of a property in a variable this can be recalled from multiple blocks, however the value of the variable cannot be changed.

$background: red;
$background-modifier: yellow;
$background-hover: blue;

.block {
  background-color: $background;

  &:hover {
    background-color: $background-hover;
  }

  &--modifier {
    background-color: $background-modifier;
  }
}

Enter fullscreen mode Exit fullscreen mode

SCSS, CSS Var

Everything changes with CSS variables, as w3c explains:

CSS variables have access to the DOM, which means that you can create variables with local or global scope, change the variables with JavaScript, and change the variables based on media queries.

:root {
  --background: red;
}

.block {
  background-color: var(--background);

  &:hover {
    --background: blue;
  }

  &--modifier {
    --background: yellow;

    &:hover {
      --background: purple;
    } 
  }
}
Enter fullscreen mode Exit fullscreen mode

The previous example highlights all the potential and order that the CSS vars guarantee.
Let's assume we have to adapt the whole website for dark mode too ... nothing simpler:

:root {
  --background: red;
}

@media (prefers-color-scheme: dark) {
  :root {
    --background: grey;
  }
}

.block {
  background-color: var(--background);

  &:hover {
    --background: blue;
  }

  &--modifier {
    --background: yellow;

    &:hover {
      --background: purple;
    } 
  }
}
Enter fullscreen mode Exit fullscreen mode

Tips:

Consider local or global vars scope, think about what it is better to declare global and therefore have it available throughout the project and what to declare within a block as local, making "economy".

Top comments (2)

Collapse
 
aalphaindia profile image
Pawan Pawar

Good one!!

Collapse
 
aka_tamer profile image
Tamer

Thank you Pawan for your feedback, do you already use 'custom properties' or are you considering to start using it?