简体   繁体   中英

CSS and jQuery have different widths

I'm, setting up the mobile side of a website at the moment, and I need custom CSS and Javascript for mobile, so in the CSS I have rules using @media screen and (max-width: 500px) { and in Javascript I was going to use if ($(window).width() < 500 .

However, if I resize my browser to the exact pixel the mobile CSS starts being used and I console.log($(window).width()); I get 485.

Is this normal behaviour or am I doing something wrong?

Update:

Using this, the values seem to be in sync, only tested in firefox though at the moment.

var scrollBarWidth = false;


function mobileRules() {

    if (!scrollBarWidth) {
        var widthWithScrollBars = $(window).width();
        $('body').css('overflow', 'hidden');
        var widthNoScrollBars = $(window).width();
        $('body').css('overflow', 'scroll');
        scrollBarWidth = widthNoScrollBars - widthWithScrollBars;
        console.log('Width: '+widthWithScrollBars+'. Without: '+widthNoScrollBars+'. Scroll: '+scrollBarWidth);
    }

    console.log($(window).width()+scrollBarWidth+' vs '+globals.mobile_width);

    if ($(window).width()+scrollBarWidth < globals.mobile_width) {
        console.log('Running mobile rules in jQuery');
    }
}

In firefox, media queries consider the width of the scrollbar to be inside the screen width.

This is what gives you the 15px wider screen width.

In webkit based browsers they don't.

If you're interested in why this thing happens, I'll quote this comment of this article :

A problem with Webkit browsers (that aren't following spec) is that the browser can encounter an infinite loop condition caused by media queries, which leads to a browser crash.

For example: >500px overflow-y: scroll, <500px overflow-y: hidden. Size your browser to 505px window width. Since the scroll bar subtracts 15 or so pixels from the width used by the media query, the media query flips you to < 500, but as soon as you hit <500 the scrollbar goes away, and the media query flips you to >500, and then the fun starts because now you have a scroll bar again and you're <500px and you get that style with no scroll bar... Rinse and repeat until the browser finally dies.

Now, write some javascript to calculate the media query max widths, and you have a page that will crash Chrome/Safari as soon as you load it.

My guess is that the spec was written the way it was to prevent this condition. Firefox & Opera are following spec, it's not really their fault you don't agree with spec.

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