root variables css code example

Example 1: css set variable

:root {
  --main-bg-color: coral;
}

#div1 {
  background-color: var(--main-bg-color);
}

#div2 {
  background-color: var(--main-bg-color);
}

Example 2: create variable in css

:root {
  --tab-count: 5;
}

#div1 {
  width: calc(100% - var(--tab-count));
}

Example 3: css variables

:root {
  --background-color: #333;
  --text-color: #fff;
}
body {
  background-color: var(--background-color);
  color: var(--text-color);
}

Example 4: css variables

/* "css variables" */
/* not for ie but good for Edge and other browser :D */

/*
 By declaring a custom property on the :root pseudo-class
 and using it where needed throughout the document
*/
:root {
  --primary-bg: #8a2be2;
  --btn-font-size: 18px;
  --btn-padding: 10px 15px;
}

.btn-primary {
  background-color: var(--primary);
  font-size: var(--btn-font-size);
  padding: var(--btn-padding);
  color: #E2E2E2;
}

Example 5: javascript use css custom properties

Values in JavaScript
To use the values of custom properties in JavaScript, it is just like standard properties.
// get variable from inline style
element.style.getPropertyValue("--my-var");

// get variable from wherever
getComputedStyle(element).getPropertyValue("--my-var");

// set variable on inline style
element.style.setProperty("--my-var", jsVar + 4);

Example 6: css variables

:root {
  --blue: #1e90ff;
  --white: #ffffff;
}

body { background-color: var(--blue); }

h2 { border-bottom: 2px solid var(--blue); }

.container {
  color: var(--blue);
  background-color: var(--white);
  padding: 15px;
}

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}

Tags:

Css Example