Resetting Meta Viewport tag at certain media query breakpoints
This was a recent question that was asked on Stack Overflow.
I’m working on a responsive layout that uses the following bit of code:
<meta name="viewport" content="initial-scale=1.0; width=device-width;">
The designer built layouts for Large Desktop (1370px wide), Small Desktop (990px) and Tablet (620px). The assumption is that Mobile (<620px) will use the Tablet version but scale it.
How would I do that, though? Because the viewport’s width is set to
device-width
, it loads the smallest stylesheet but doesn’t scale it.tl;dr — Is there any way to tell a mobile browser to disregard the
width=device-width
value and instead scale the website to fit when the viewport is smaller than a certain value?
First off this isn’t really the best approach for a typical responsive design. If you build mobile first and set the widths to % then it will avoid any issues that you might be having because the content will scale to the device width.
If you really want to go down the other path though you could alter the meta viewport element using javascript and use enquire.js to dictate when that would occur….
<script>
enquire.register("screen and (max-width:619px)", {
match : function() {
$('meta[name=viewport]').attr(
'content',
'width=620; initial-scale=1.0'
);
},
unmatch : function() {
$('meta[name=viewport]').attr(
'content',
'width=device-width, initial-scale=1.0'
);
},
});
</script>
Now I probably should have tested this, but I actually think it’s the wrong approach to the problem. What’s most important is that it doesn’t matter what I think, there is still a way to achieve the solution this developer happens to be looking to answer.
You might have noticed that we pull through the latest questions on stack overflow on the home page of this site. I encourage anyone with a few minutes to visit and answer any questions that you can to keep people building better responsive sites.