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 clicked, the link would remove all media query styles and reset the page to default styles, exposing the site as it would at 1024px wide. Is there a way to achieve this?
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.
来源:https://stackoverflow.com/questions/14148836/can-all-media-queries-be-overriden