Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!