简体   繁体   中英

JavaScript media query vs CSS media query

I've noticed that the JavaScript media query takes effect after the CSS equivalent ones.

I've created an example demonstrating what I'm talking about:

HTML:

<div class="foo">
  bar
</div>

CSS:

@media(max-width: 300px) {
  .foo {
    background-color: blue;
  }
}

.foo {
  background-color: green;
}

JavaScript:

const w = window.matchMedia("(max-width: 300px)");
const div = document.querySelector(".foo");
function fun(e) {
  if (e.matches) {
     div.style.backgroundColor = "red"
  } else {
     div.style.backgroundColor = "green"
  }
}


w.addListener(fun);

jsbin link is: here

Here red background color overrides the blue(which is set using CSS media query) when the screen width is below or equal to 300px.

I think it's a good thing. But I'm not sure, is it the standard well supported behavior? Is it safe to build logic based on this behavior?

This is part of the CSS specificity

Inline styles added to an element ( eg, style="font-weight: bold;" ) always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity .

The javascript code you posted will add inline styles ( through the style property of the element ) and thus has the highest specificity. ( it has nothing to do with the js media query, it just has to do with how you apply the style in the JS to the element )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM