DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

CSS Variables end to end

-> var() used to insert CSS variables.
-> we can create local and global variables.
-> CSS variables can have access to DOM.
-> We can change variables with javascript.
-> We can change local and global variables based on media queries.
-> Good Example: Creating variables for colors used across application.
-> Syntax: var(--var_name, default_value);
-> variable name must starts with (--) dash dash.
-> Local variables overrides global variables.

Example:

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Project</title>
  </head>
  <body>
    <div class="first" id="first">1</div>
    <div class="second" id="second">2</div>
    <script src="script.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

/* styles.css */

/* Creating Global variable */
:root {
  --blue: lightblue;
  --black: black;
}

.first {
  --color: red; /* local variable */
  border: 4px var(--blue) solid; /* global variable used */
  background-color: var(--black);
  padding: 20px;
  margin: 10px;
  color: var(--color); / * local variable used */
}

.second {
  --blue: blue; / * global variable is overridden by local variable */
  --color: cyan;
  border: 4px var(--blue) solid; /* overridden global variable used */
  background-color: var(--black);
  padding: 20px;
  margin: 10px;
  color: var(--color);
}

@media screen and (max-width: 580px) {
  .first {
    --color: white; /* local variable updated inside media query */
  }
  .second {
    --color: green;
  }
  :root {
    --blue: gray; /* global variable updated inside media query */
  }
}

Enter fullscreen mode Exit fullscreen mode

//script.js

const first = document.getElementById("first");
const second = document.getElementById("second");

first.addEventListener("mouseover", () => {
  let r = document.querySelector(":root");
  r.style.setProperty("--blue", "yellow");
});

second.addEventListener("mouseover", () => {
  let r = document.querySelector(":root");
  r.style.setProperty("--black", "pink");
});

Enter fullscreen mode Exit fullscreen mode

Initial:

Image description

Media query: at 580px width

Image description

Mouse Over on First:

Image description

Mouse Over Second:

Image description

Thanks,
Vishwak

Top comments (0)