How can I add pre-defined values in CSS? As if it were a variable to store.
For example, a color (hex or RGB) so I could use it in the rest of the document, so instead of typing the color value, I would just type the name of the "variable".
How can I add pre-defined values in CSS? As if it were a variable to store.
For example, a color (hex or RGB) so I could use it in the rest of the document, so instead of typing the color value, I would just type the name of the "variable".
You can do this by creating specific classes for this.
For example, in your CSS you create a class with the name preto
, and with the value hex
of the black color:
.preto {color:#000;}
In HTML you just call the class as follows:
.preto {color:#000;}
.vermelho {color:#ff0000;}
/* e por aí em diante ... */
<div class="preto">Olá, eu sou uma classe com o texto com a cor preta</div>
<div class="vermelho">Olá, eu sou uma classe com o texto com a cor vermelha</div>
So far it is not possible to define values in the same way that we are accustomed to declaring variables, at least not cross-browser . One way to simulate this is to create classes that contain the properties that would be applied to the element, as shown by Chun.
Another alternative is to use preprocessors , but then I'd be running away from the subject of the question that is declare values in the css file itself.
Well, there is a project in the specification with the aim of making it possible to declare variables in style sheets , similar to the way less and sass work. And the assignment of the value will be by the attribute var()
, eg: background-color: var(--meu-bg)
.
Firefox and Chrome already have the deployed feature , but remember that it's still an experiment technology . In this MDN article there are more objective explanations about the reason for the implementation and what problems it aims to solve.
Note : In Chrome this feature needs to be enabled by accessing the chrome://flags
.
If you're using Firefox, the snippet below will work and you'll see the use of the variables in action:
:root {
--cor-links: red;
--borda: 2px solid blue;
--sombra: 0 0 10px 5px rgba(0,0,0,.5);
}
a {
color: var(--cor-links)
}
div {
border: var(--borda);
box-shadow: var(--sombra);
}
<a href='#'>Meu Link vermelho</a>
<br><br>
<div>Meu div com borda azul e sombra.</div>