Make your CSS dynamic with custom properties

keyur koladiya

Oct 02, 2020

2 min readLast Updated May 03, 2022

How to create Dynamic CSS?

While writing CSS sometimes we need to declare variables, CSS custom properties are like CSS’s own implementation of variables.

What are CSS custom properties?

CSS custom properties allow you to assign arbitrary values to a property with a name of your choice It allow you Use the var() function to use these values in other properties

Prerequisites

  • Basic knowledge of CSS
  • You should have knowledge of currentColor refers to the current color value of an element

Implement Custom CSS Properties

  • How to create a pre/postprocessor variables
  • How to use Variable

How to Create pre/post processor Variables

  • CSS pre/postprocessors are allow to store values in a keyword.
  • It also scoped the keyword to a certain selector if required.
  • This enables you to store color codes, sizes with all of the known units.
  • var() function has been used to get the value of the custom property.
  • We can not use var() functions for selectors, property names, or media query declarations.
  • CSS pre/postprocessor variables are only used at compilation-time.
  • CSS variables can be used and updated dynamically.

The syntax for CSS custom properties is a bit weird compared to other languages, for example :

:root {
  currentColor: #D3D3D3;
}

.section {
  background: var(currentColor);
}

CSS variables can be used and updated dynamically, illustrate with below example

:root {
  $value: 10px;
}

.radius {
  border-radius: $value;
}

@media screen and (min-width: 600px) {
  $value: 50px;
}

This snippet of SASS declarations and rules compiles to CSS as follows:

.radius {
  border-radius: 10px;
}

How to use Variable

Some Basic CSS custom variables we are using in CSS since a long time is currentColor keyword, It can be used on any declaration that accepts a color value, and it cascades perfectly.

Example

.section {
  color: red;
  border: 1px solid currentColor; 
}
.section .item {
  background: currentColor; 
}
 
.section .item.blue {
  color: blue;
}

Explanation of above Example  :

  • Create element with color : red
  • Sets a red background color for every span child of .element, unless a color property is declared in this same block

Projects Completed till now.

Discover how we can help your business grow.

"Third Rock Techkno's work integrates complex frameworks and features to offer everything researchers need. They are open-minded and worked smoothly with the academic subject matter."

- Dr Daniel T. Michaels, NINS

Related Resources

Our Services

You May Also Like