Is it possible to create predefined values in css?

2

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".

    
asked by anonymous 06.10.2015 / 23:18

3 answers

3

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>
    
06.10.2015 / 23:43
3

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>
    
19.02.2016 / 19:02
0

Yes, but not directly in CSS.

You should implement {LESS} or Saas > to get it.

These technologies support you to create variables and logic where they generate a css from predefined values.

    
19.02.2016 / 19:16