Can all media queries be overriden?

前端 未结 1 1541
半阙折子戏
半阙折子戏 2021-01-15 18:54

I have built a responsive website with media queries to target different mobile devices but would like to have an \"override all\" link available on smaller devices. When cl

1条回答
  •  日久生厌
    2021-01-15 19:19

    The only way you can do this is with Javascript. I came up with two solutions:

    id/class on element:
    Apply an id or class to the html element: .
    In your media-queries, every selector will start with .media-queries:
    CSS

    @media (max-width: 300px) {
        .media-queries #nav li {
            display: block;
        }
        .media-queries #main, .media-queries #aside {
            float: none;
        }
    }
    

    Then, you get JS to remove class="media-queries".
    HTML

    Default style
    

    JavaScript

    var delMQ = document.getElementById('del-mq');
    delMQ.onclick = function() {
        document.getElementsByTagName('html')[0].removeAttribute('class');
    }
    

    jQuery

    $('#del-mq').click(function() {
        $('.media-queries').removeClass();
    });
    


    Pros: no extra http requests.
    Cons: lots of css selectors(.media-queries), which shouldn't be a problem if using Sass:

    @media (max-width: 300px) {
        .media-queries {
            #nav...
            #main...
        }
    }
    



    External media-queries.css
    All the media queries go in a separate css file. Include it with .
    Then you get an ID for the and remove the element.
    HTML

    
        
        
    
    
        ...
        Default style
        ...
    
    

    Javascript

    var delMQ = document.getElementById('del-mq');
    delMQ.onclick = function() {
        document.getElementsByTagName('head')[0].removeChild(document.getElementById('media-queries'));
    }
    

    jQuery

    $('#del-mq').click(function() {
        $('#media-queries').remove();
    });
    



    Pros: no need for lots of css selectors.
    Cons: extra http request.

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