Home > Net >  How to declare variables in css
How to declare variables in css

Time:09-07

Can anyone tell me why it is declared var(--color), what is the difference in declaring only the variable?

Ex:

color: var(--color, var(--blue));

CodePudding user response:

When you use the variable without var you set the value to the variable

:root {
  --color: red; /* set a value "red" to the "color" variable */
}

If you want then to get a value from the variable, you need to use var:

.card {
  color: var(--color);  /* get a color from the "--color" variable */
}

From the MDN Docs:

Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);).

An example:

:root {
  --color: red; /* set default value for "color" variable */
}


#primary-cards {
  --color: #0F0; /* set custom value for "color" variable in primary cards */
}

.card {
  color: var(--color);  /* use the color variable */
}
<section id="primary-cards">
  <div class='card'>
    My card content
  </div>
</section>

CodePudding user response:

<!DOCTYPE html>
<html>
<head>
<style>
  :root{
       /* --color: rbg)1,2,3,4);  error code, or --color variable doesn't exist */
      --blue: blue;
      
      --display-color: red;
      --NoFallBack-to-blue: blue;
      
      }
      
   .red{
      color: var(--display-color, var(--NoFallBack-to-blue))
      }
      
   .blue{
      color: var(--color, var(--blue))
      }
     
</style>
</head>
<body>

<div >
  <p> color will not fallback to blue </p>
</div>


<div >
  <p> color will fallback to blue </p>
</div>


</body>
</html>

My bad, I didn't read the question, I only read the css code.

You can create a block of css root and assign a value to the declared variable.

For example:

:root {

   --color: rgb(53, 52, 52); 


  /* for fall back */
  --blue: #0000FF;
}

Inside a css selector, let's call the variable

.className{
   
    color: var(--color);
}

lets say --color doesn't exist or forgot to assign a value to the variable.

:root {

       --color: ; 
  
    
      /* for fall back */
      --blue: #0000FF;
    }

It is a fallback when first value doesn't work out then the program will fallback to next value which is --blue. The var(--blue) will display on the screen

.className{

    color: --var(--color, var(--blue))
}
  •  Tags:  
  • css
  • Related