bonaca bonaca - 3 months ago 7
CSS Question

window width - css vs javascript

<link rel="stylesheet" href='media700.css' media="screen and (max-width:700px)">


JS

var a = window.outerWidth;
console.log(a); // 711


According the javascript calculation at the moment of switching stylesheet
media700
is used on 711px and not 700px window width.

Answer

Just use innerWidth instead and you will see they share the same value.

As soon as you reach 700px and lower you will see the text 700px using a css media query and a background change with js.

Resize the demo in full page view.


jsfiddle


$(window).on("resize", function() {
  var innderWidth = $(this).innerWidth();
  $("span").text(innderWidth + "px");
  if (innderWidth <= 700) {
    $("body").css("background-color", "gold");
  } else {
    $("body").css("background-color", "");
  }
});
body {
  margin: 0;
}
p {
  margin: 0;
  background-color: dodgerblue;
  font-size: 3em;
}
@media (max-width: 700px) {
  body::after {
    font-size: 10em;
    content: "700px";
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Window inner width: <span></span>
</p>