/    /  CSS Variables

CSS Variables

 

The CSS variables are helpful to add the values of custom property to our web page. Custom properties are sometimes mentioned as cascading variables or CSS variables.

 

The var() function:

 

The var() function in CSS is used to insert the custom property value(CSS variable). The name of the CSS variable can be passed as the argument to the var() function.

 

Syntax:

 

var( --custom-name, value )

 

Parameters:

 

  • –custom-name : Name of the custom property(two dashes (–)
  • value : The substitution when the custom property is invalid.

 

Example:

 

<!DOCTYPE html>
<html>
  <head>
    <title>CSS Variables</title>

     <style>
      :root          
        --bg-color: green;
        --text-color: white;
       }
             
       /* var() function used here */
       body {
        background-color: var(--bg-color);
       text-align: center;
      }
      h1 {
        color: var(--text-color);
      }
      div {
        color: var(--text-color);
      font-size: 30px;
      }
    </style>
  </head>
  <body>
    <h1>Welcome to the I2Tutorials</h1>
         
    <div>
      Example of CSS variables
                     <h3>--bg-color: green;</h3>
                     <h3>--text-color: white;</h3>

                                   
    </div>
  </body>
</html>

 

OUTPUT:

 

CSS Variables

 

Example:

 

Use the fallback values.

 

<!DOCTYPE html>
<html>
  <head>
    <title>CSS Variables</title>

    <style>
     :root {
       --bg-color: green;
     }
     body {
      background-color: var(--bg-color);
      text-align: center;
     }
     h1 {
       color: var(--text-color, white);
     }
     div {
       color: var(--text-color, white);
       font-size: 30px;
      }
   </style>
 </head>

  <body>
    <h1>Welcome to the I2Tutorials</h1>

    <div>
      Example of CSS variables
      <h3>--bg-color: green;</h3>

    </div>

  </body>
</html>

 

OUTPUT:

 

CSS Variables

 

Use of calc() with the var():

 

Adjust the padding and font-size of the elements.

 

Example:

 

<!DOCTYPE html>
<html>
<head>
<title>CSS Variables</title>

<style>
:root {
--bg-color: green;
--extra-padding: 1.2em;
--txt-size: 90px;
}
body {
background-color: var(--bg-color);
text-align: center;
}
h1 {
color: var(--text-color, white);
font-size: calc(var(--txt-size) - 20px);

}
div {
color: var(--text-color, white);
font-size: 30px;
border: 8px ridge red;
padding: calc(var(--extra-padding) + 20px);
}
</style>
</head>

<body>
<h1>Welcome to the I2Tutorials</h1>

<div>
Using the calc() function with the var() function
</div>

</body>
</html>

 

OUTPUT:

 

CSS Variables