Select Page

CSS Variables make code easier to read and change values throughout the project. CSS variables have access to the DOM, which you can change with JavaScript and on media queries.


DEMO:

Open demo in a full window – https://demos.webdevpuneet.com/css/css-variables/index.html


HTML

<!DOCTYPE html>
<html>
<head>
<style>
:root {
  --blue: #1e90ff;
  --white: #ffffff; 
  --width: 300px;
  --height: 300px;
}

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

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

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

button {
  background-color: var(--white);
  color: var(--blue);
  border: 1px solid var(--blue);
  padding: 5px;
}
</style>
</head>
<body>

<div class="container">
  <h2>CSS Variables</h2>
  <p>CSS variables make code easier to read and change values throughout the project. CSS variables have access to the DOM, which you can change with JavaScript and on media queries.</p>
  <p>
    <button>Yes</button>
    <button>No</button>
  </p>
</div>

</body>
</html>

CSS variables can have a global or local scope

Defining a variable in Global scope

To create a variable with global scope, declare it inside the :root selector. The :root selector matches the document’s root element.

:root {
  --blue: #1e90ff;
  --white: #ffffff; 
  --width: 300px;
  --height: 300px;
}

Defining a variable in the local scope

To create a variable with local scope, declare it inside the selector that is going to use it.

.section1{
  --font-size: 24px;
  --leading: 1.8;
  font-size: var(--font-size);
  line-height: var(--leading);
}
 
.section2{
  --font-size: 18px;
  --leading: 1.6;
  font-size: var(--font-size);
  line-height: var(--leading);
}