Variables en CSS

¡Muévase sobre Sass, tenemos variables #CSS! Todavía amo a Sass, por supuesto. Pero es genial CSS nativo soporta esto. No necesita un preprocesador y no más compilaciones 🥳

El alcance global le permitirá acceder a la variable en todas partes. El alcance local solo estará dentro de su selector específico 👍

:root {
  /* 1. Defining in Global Scope */
  –color: red;  /* 2. Available in all selector*/
  color: var(–color); /* red */
}.local {
  /* 1. Defining in Local Scope */
  –color: blue;  /* 2. Scoped to the .local class only */
  color: var(–color); /* blue */
}

Tiempo de cuentos…

Ha pasado un tiempo desde que tuve la hora de la historia, así que permítanme compartir el viaje de un desarrollador de CSS descontento que finalmente dejó de estar tan enojado 😂

Código CSS duplicado Yucky

En aquellos días, recuerdo tener que hacer muchos estilos duplicados …

.subtitle {
  color: #999;
}
.subtext {
  color: #999;
}

¡Esto siempre fue molesto para mí! Porque conocí el concepto de variables desde otro lenguaje de programación. Así que siempre me estremezco cuando veo esta duplicación.

Sass al rescate 🦸‍♀️

Y luego descubrí a Sass. ¡Y finalmente puedo usar variables!

$secondary-color: #999;.subtitle {
  color: $secondary-color;
}
.subtext {
  color: $secondary-color;
}

Todo esto fue genial. Pero luego debe lidiar con la instalación de Sass en su proyecto y la sobrecarga de lidiar con un preprocesador y compilar. Y para un proyecto pequeño, el esfuerzo de configurar Sass simplemente no tiene sentido. Entonces, volviendo a ser un desarrollador quejumbroso y tuiteando una tormenta de fuego sobre cómo CSS es molesto … porque es por eso que Twitter se creó correctamente, es un lugar para que los desarrolladores enojados se desahoguen 😅

Sass, CSS es mi héroe 💪

CSS finalmente tuvo suficiente de mí enviándole mala energía. Entonces introdujo las variables CSS. Ahora puedo establecer una variable de forma nativa. Sin preprocesador, sin instalación adicional, simplemente CSS listo para usar. Hermoso no es así 😍

:root {
  –secondary-color: #999;
}
.subtitle {
  color: var(–secondary-color);
}
.subtext {
  color: var(–secondary-color);
}

¿Me puedo quejar de la sintaxis incómoda? Claro … pero la gratitud es el camino a la felicidad. Así que voy a sumergirme en este cielo variable por un momento … hasta la próxima hora del cuento 😂

Sintaxis Variable CSS

1. Declarando una variable CSS

Prefijas tu nombre de variable con 2 guiones, -.

–variable-name: some-value;

2. Usando la variable CSS

Y para usarlo. Usted usa pasar el nombre de su variable a var ().

css-property: var(–variable-name);

Ámbitos en la variable CSS

Puede declarar su variable CSS en el ámbito global, lo que significa que puede estar disponible en toda su aplicación. O simplemente puede establecer la variable CSS en el ámbito local, donde solo está disponible en el selector específico.


Global Scope 

Para declararlo en el ámbito global, primero establece su definición dentro: root {}.

:root {
  –primary-color: #000;
}h1 {
  color: var(–primary-color);
}

Local Scope

To declare it in the local scope, you just define your variable inside your element block. And that variable is only available within that selector. If you tried to use is somewhere, it won’t have any effect.

h2 {
  –h2-color: #999;
  color: var(–h2-color);
}h3 {
  /* No Effect */
  color: var(–h2-color);
}

Examples

Let’s go over some different ways you can have some fun defining CSS variables ✅
You can set multiple value

:root {
  –margin: 10px 20px;
}div {
  margin: var(–margin);
}

You can build up values

:root {
  –value: 5;
}div {
  padding: var(–value) px; /* 5px */
}

This is handy when used it with calc(). Are you sensing some cool dynamic sizing application with this. Ya, my spidy senses are tingling too! 🕷

div {
  padding: calc(var(–value) * 2px); /* 10px */
}

You can reference variable in another definition

:root {
  –border-width: 10px;
  –border: var(–border-width) solid #000;
}div {
  border: var(–border);
}

After some testing, I found the order doesn’t matter. You can reference a latter variable in an earlier definition. But coming from JavaScript where you should always use the variable after it’s been defined, this seems a bit off to me  😅

/* This also works */
:root {
  –border: var(–border-width) solid #000;
  –border-width: 10px;
}

Overriding CSS Variable Values

The great thing is you can override the global value, so can set something unique to a specific context.

:root {
  –default-color: pink;
}.content {
  /* Override the global css variable */
  –default-color: green;
}p {
  color: var(–default-color);
}<p>Default “Pink” color</p><div class=”content”>
  <p>Overridden “Green” color</p>
</div>

Setting Fallback Value

What happens when you use a variable that has never been assigned 🤔

p {
  color: var(–color);
}

The answer is NOTHING. Your app doesn’t break. I guess that’s nice. But if that seems a bit risque, you can set a Fallback Value.

p {
  color: var(–color, pink);
}<p>Pink color</p>

And if you do define it, the defined color will just take over.

p {
  –color: black;
  color: var(–color, pink);
}<p>Black color</p>

Using CSS Variable in JavaScript

The best thing about using CSS variable instead of Sass variable, is that you can access it in JavaScript! And you know when JS joins the party, it’s going to get crazy 😆

Let’s go over the basics usage and see how we can retrieve and set our CSS variables.
Retrieve from inline style

If you set your CSS variable via inline style.

<p style=”–color: red”></p>

Then you retrieve your value with getPropertyValue():

// Get our <p> element
const element = document.querySelector(‘p’);// Retrieve our CSS variable “–color”
element.style.getPropertyValue(‘–color’); // ‘red’

Retrieve from inline or css file

If you set your CSS variable in your style tag or an external CSS file.

<style>
  p {
    –color: red;
  }
</style>

Then you need to use this first getComputedStyle():

// Get our <p> element
const element = document.querySelector(‘p’);// Retrieve our CSS variable “–color”
getComputedStyle(element).getPropertyValue(‘–color’); // ‘red’

And yes, you can also use this way to retrieve your inline style as well:

<p style=”–color: red”></p>// Get our <p> element
const element = document.querySelector(‘p’);// Retrieve our CSS variable “–color”
getComputedStyle(element).getPropertyValue(‘–color’); // ‘red’

Setting a CSS Variable with JS

// Get our <p> element
const element = document.querySelector(‘p’);// Set our “–color” variable to be “blue”
element.style.setProperty(‘–color’, ‘blue’);

Simple Example

Let’s put everything together and look at a simple example. Here we want to check our text color when the text is clicked.

<p style=”–color:red; color: var(–color)”></p>// Get our <p> element
const element = document.querySelector(‘p’);// On click, change text from “red” to “blue”
element.addEventListener(‘click’, function() {
  element.style.setProperty(‘–color’, ‘blue’);
});

Browser Support

Beside party 💩 Internet Explorer, the rest of the browsers are all game!

    Browser Support: CSS Variables

Community Input

@lisovskyvlad: IE11 🙁 There’s JS polyfill but on our experience, it makes ie11 so slow, it’s hardly possible to use 🙁

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Uso de cookies

Este sitio web utiliza cookies para que usted tenga la mejor experiencia de usuario. Más info

aceptar