Make @media max-width behave the same as $(window).width
While working on a website I encountered a major frustrating, yet logical
problem.
Take a look at this fiddle.
Important CSS:
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
}
div#wrapper {
padding: 1em;
}
img {border: 4px solid blue;}
@media screen and (max-width: 480px) {
img {border: 0 none;}
}
Important jQuery:
function imgSize() {
if ($(window).width() < 481) {
$("img").css({
"position": "relative",
"width": $(window).width(),
"max-width": "none",
"left": "-1em",
"float": "none"
});
} else {
$("img").attr("style", "");
}
}
imgSize();
$(window).resize(function() {
imgSize();
});
Try making the result window smaller than 481px and bigger again. Basic
functionality explained: When the window is smaller than 481px in width,
the image will be forced a width that's larger than its parent and equal
to the window width. You cannot do this with CSS. (If you can, please tell
me!) This should give a nice view on mobile devices. To further "beautify"
the image, the original border is removed when the screen is between zero
and 480px, this is done by media queries.
All of this works great, until ... a wild scrollbar appears! What happens
is that jQuery only takes the "window" into account, whereas the media
query also counts the pixels generated by the width of the scrollbar.
Actually, this is quite logical. $(*window*).width() and @media *screen*
but it's super frustrating. What is the best way to deal with this issue?
Write a custom function in jQuery that comes down to "if scrollbar: add x
pixels to the "if window width"-function" in which x is the width of the
scrollbar in a specific operating system. Or should we try to bypass this
with CSS, or just not using jQuery and CSS interchangeably?
I am not focusing on this issue alone, but on the difference between
$(window).width() and media queries in general. In my case, I could
actually add border: 0 none to the jQuery and that's that. But
unfortunately that's not always possible.
No comments:
Post a Comment