root css variables 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: css variable

:root {
  --main-bg-color: pink;
}
body {
  background-color: var(--main-bg-color);
}

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: :root css

/*In HTML4, this is always the <html> element, since it is the highest-level
ancestor of all other elements on the page. So, :root is identical to using the
html as a selector, except that it has a higher specificity.
This means that, in the following example, the styles specified using :root
will override those specified using the html selector, even if the latter
comes next in the style sheet.
In document formats other than HTML, such as SVG and XML, 
the :root pseudo-class can refer to another higher-level ancestor.*/

:root {
    /* style the root element */
}

html {
    /* style the root element */
}

Example 6: use of root in css

:root can be useful for declaring global CSS variables:
:root {
  --main-color: hotpink;
  --pane-padding: 5px 42px;
}

Tags:

Misc Example