Why is the window.width smaller than the viewport width set in media queries

后端 未结 7 1991
轻奢々
轻奢々 2020-12-01 09:45

I am quite puzzled and still unsure how to explain this in proper words. So far i\'ve used and set up my media queries with Breakpoint. An used Breakpoint-variable looks lik

相关标签:
7条回答
  • 2020-12-01 10:11

    Similar to @Snugugs's answer but worked better for my use case:

    CSS (Note I am using LESS so @tabletMin and @desktopMin translate to breakpoint variables I have set elsewhere:

        #cssWidth {
            display:none;
            content:'mobile';
        }
    
        /* Responsive styles (Tablet) */
        @media (min-width: @tabletMin) {
            #cssWidth {
                content:'tablet';
            }
            /* Other tablet CSS... */
        }
        /* Responsive styles (Desktop) */
        @media (min-width: @desktopMin) {
            #cssWidth {
                content:'desktop';
            }
            /* Other Desktop CSS... */
        }
    

    And then in JS:

        getView = function() {
            // If #cssWidth element does not exist, create it and prepend it do body
            if ($('#cssWidth').length === 0) {
                $('body').prepend($(document.createElement('div')).attr('id', 'cssWidth'));
            }
            // Return the value of the elements 'content' property
            return $('#cssWidth').css('content');
        };
    

    The getView() function will then return the string 'mobile', 'tablet' or 'desktop' dependant on the width the media queries see.

    This could be extended to fit more viewport widths, just add more rules in the CSS with other values.

    0 讨论(0)
提交回复
热议问题