20. CSS usando variables en Media Queries

Ahora vamos a cambiar los valores de variables en consultas de medios (media query). Aquí, primero declaramos una nueva variable local llamada —fontsize para la clase .container. Establecemos su valor en 25 píxeles. Luego lo usamos en la clase .container más abajo. Luego, creamos una regla @media que dice «Cuando el ancho del navegador es de 450 px o más, cambie el valor de la variable —fontsize de la clase .container a 50 px».

Ejm

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
/* Variable declarations */
:root {
--blue: #1e90ff;
--white: #ffffff;
}

.container {
--fontsize: 25px;
}

/* Styles */
body {
background-color: var(--blue);
}

h2 {
border-bottom: 2px solid var(--blue);
}

.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
font-size: var(--fontsize);
}

@media screen and (min-width: 450px) {
.container {
--fontsize: 50px;
}
}
</style>
</head>
<body>
<h1>Using Variables in Media Queries</h1>

<div class="container">
<h2>Lorem Ipsum</h2>
<p>
When the browser's width is less than 450px, the font-size of this div
is 25px. When it is 450px or wider, set the --fontsize variable value to
50px. Resize the browser window to see the effect.
</p>
</div>
</body>
</html>

Aquí hay otro ejemplo donde también cambiamos el valor de la variable –blue en la regla @media.

Ejm

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
/* Variable declarations */
:root {
--blue: #1e90ff;
--white: #ffffff;
}

.container {
--fontsize: 25px;
}

/* Styles */
body {
background-color: var(--blue);
}

h2 {
border-bottom: 2px solid var(--blue);
}

.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
font-size: var(--fontsize);
}

@media screen and (min-width: 450px) {
.container {
--fontsize: 50px;
}
:root {
--blue: lightblue;
}
}
</style>
</head>
<body>
<h1>Using Variables in Media Queries</h1>

<div class="container">
<h2>Lorem Ipsum</h2>
<p>
When the browser's width is 450px or wider, set the --fontsize variable
value to 50px and the --blue variable value to lightblue. Resize the
browser window to see the effect.
</p>
</div>
</body>
</html>
Scroll al inicio