Mejora tu responsive web design con variables CSS

Las variables CSS pueden ofrecerte mejores resultados que las variables Sass en Responsive Web Design.

Diseño web
3 minutos
Hace 7 años
Mejora tu responsive web design con variables CSS

¡Accede a cientos de cursos
con solo un pago al año!

Blog Microbanner

Las variables CSS son increíbles y su mejor característica es que están vivas en el navegador, lo que permite manipularlas con JavaScript o utilizarlas para hacer un mejor Responsive Web Design (como te enseñaré en este artículo).

Variables CSS en el navegador

Supongamos que nuestro diseño tiene un .main-header fijo en la parte superior del viewport y una altura diferente en móvil y desktop. Con el CSS de toda la vida lo escribimos así:

1.main-header { 2 height : 3rem; 3} 4 5@media screen and (min-width: 64em) { 6 .main-header { 7 height : 4rem; 8 } 9} 10

Puesto que este elemento es fijo, debemos empujar el body para que no haya elementos que queden tapados por el.

1.main-header { 2 height : 3rem; 3} 4 5body { 6 margin-top : 3rem 7} 8 9@media screen and (min-width: 64em) { 10 .main-header { 11 height : 4rem; 12 } 13 body { 14 margin-top : 4rem 15 } 16} 17

En este punto la cosa se empieza a complicar porque debemos cambiar valores en dos lugares distintos, y con que el proyecto crezca y otros elementos dependan de este valor, mantener el código será un caos (clásico de CSS 😄). Sería mejor guardar esa altura en una variable. Seguro piensas en Sass:

1$header-height: 3rem; 2 3.main-header { 4 height : $header-height; 5} 6 7body { 8 margin-top : $header-height; 9} 10 11@media screen and (min-width: 64em) { 12 $header-height : 4rem; 13} 14

Pero hay malas noticias: el código anterior no funciona. Las variables Sass nunca se compilan (solo se compilan sus valores cuando son utilizados en alguna declaración). Así que la forma correcta de hacerlo con Sass es la siguiente:

1$header-height : 3rem; 2 3.main-header { 4 height : $header-height; 5} 6 7body { 8 margin-top : $header-height; 9} 10 11@media screen and (min-width: 64em) { 12 $header-height : 4rem; 13 .main-header { 14 height : $header-height; 15 } 16 body { 17 margin-top : $header-height; 18 } 19} 20

Es decir, además de redeclarar la variable $header-height hay que volver a escribir las declaraciones para main-header y body 💩

Variables CSS al rescate

Puesto que las variables CSS están vivas en el navegador, pueden actualizarse en tiempo real y el navegador actualizará los valores automáticamente. Nuestro ejemplo previo quedará así:

1:root { 2 --header-height : 3rem; 3} 4 5.main-header { 6 height : var(--header-height); 7} 8 9body { 10 margin-top : var(--header-height) 11} 12 13@media screen and (min-width: 64em) { 14 :root { 15 --header-height : 4rem; 16 } 17} 18

Hermoso 😍. Podemos reducir el código un poco más (y hacerlo más entendible) usando Sass:

1:root { 2 --header-height : 3rem; 3 @media screen and (min-width: 64em) { 4 --header-height : 4rem; 5 } 6} 7 8.main-header { 9 height : var(--header-height); 10} 11 12body { 13 margin-top : var(--header-height) 14} 15

Podemos usar el mismo principio para cualquier valor que cambie en una media query, ahorrándonos mucho tiempo y esfuerzo. Además de hacer el código más legible y mantenible (nuevamente, el problema clásico de CSS). Por ejemplo, podrías crear tu propio sistema de tipografía fácilmente:

1:root { 2 --h1-font-size : 2rem; 3 --h2-font-size : 1.5rem; 4 --body-font-size : 1rem; 5 --small-font-size : .8rem; 6 7 @media screen and (min-width: 64em) { 8 --h1-font-size : 2.5rem; 9 --h2-font-size : 1.75rem; 10 --body-font-size : 1.2rem; 11 --small-font-size : 1rem; 12 } 13} 14 15h1 { 16 font-size : var(--h1-font-size); 17} 18 19h2 { 20 font-size : var(--h2-font-size); 21} 22 23body { 24 font-size : var(--body-font-size); 25} 26 27.small { 28 font-size : var(--small-font-size); 29} 30

O tu propio grid:

1:root { 2 --grid-columns : repeat(2,1fr); 3 --grid-gap : 1rem; 4 5 @media screen and (min-width: 40em) { 6 --grid-columns : repeat(3,1fr); 7 --grid-gap : 1.5rem; 8 } 9 10 @media screen and (min-width: 64em) { 11 --grid-columns : repeat(4,1fr); 12 --grid-gap : 2rem; 13 } 14} 15 16.grid { 17 display : grid; 18 grid-template-columns : var(--grid-columns); 19 grid-gap : var(--grid-gap); 20} 21

Recuerda que en EDteam tenemos un curso gratuito de variables CSS que te enseña este y más trucos. ¿Ya usas variables CSS en tus proyectos? Y si aún no, ¿qué estás esperando?

Comentarios de los usuarios