• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

147
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.

almost 3 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.

almost 3 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.

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error