Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
Can an element's class change depending on whether browser is widened or narrowed?

I want to set a class to an element during width-change, depending on whether the browser-width is widened or narrowed. If narrowed, the element receives the first class; if widened, the second.

<--- class=“narrow”     |     ---> class=“widen”

If it can be done, my first choice is CSS, else, JavaScript (or a combo of the two). I have no idea how to approach the issue, I only know that CSS media queries is not giving me what I want.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use @media. Check the size of screen, set 2 @media rules. In each rule, you can change CSS properties of the same class.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use JavaScript matchMedia method as follow:

function changeClass(x) {
    if (x.matches) { // If media query matches
        document.getElementById("myDiv").classList.add("narrow");
        document.getElementById("myDiv").classList.remove("widen");
    } else {
        document.getElementById("myDiv").classList.remove("narrow");
        document.getElementById("myDiv").classList.add("widen");
    }
}

var x = window.matchMedia("(max-width: 900px) and (min-width: 400px)")
changeClass(x) // Call listener function at run time

x.addEventListener("change", () => {
    changeClass(x);
});
.narrow {
    color: red;
}

.widen {
    color: rgb(45, 230, 45);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>

    <div id="myDiv">
        this is the div
    </div>
    
    <script src="myCode.js"></script>
</body>
</html>

If the browser width is greater than 700px it changes the class to .widen and if it is less than 700px it changes the class to .narrow.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda