Can all media queries be overriden?

前端 未结 1 1539
半阙折子戏
半阙折子戏 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 <html> element:
    Apply an id or class to the html element: <html class="media-queries">.
    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

    <a id="del-mq" href="#">Default style</a>
    

    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 <link rel="stylesheet" href="media-queries.css">.
    Then you get an ID for the <link> and remove the element.
    HTML

    <head>
        <link rel="stylesheet" href="default.css">
        <link id="media-queries" rel="stylesheet" href="media-queries.css">
    </head>
    <body>
        ...
        <a id="del-mq" href="#">Default style</a>
        ...
    </body>
    

    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)
提交回复
热议问题