33
votes

I have in a webpage which is responsive. It makes use of media queries.

But the same page loaded in an iframe is not working.

For example, consider to my webpage, I have given background color as red when the screen-width is less than 640px.

@media only screen and (max-device-width : 640px) {

    .header-text {
        background-color: red;
    }
}

So when I load that window in a new tab and make the browser width less than 640px, background color becomes red.

But the same window when loaded in an iframe of 320*480 dimensions does not have background color red.

How to make media queries work in an iframe?

4
Set viewport in the parent windows. Solution is here: stackoverflow.com/a/20838525/5016546 - Center Developments

4 Answers

40
votes

Try it this way, instead of device just target the width

Change

@media only screen and (max-device-width : 640px) {

to

@media only screen and (max-width : 640px) {

Also, it is more advised to target both min and max view-port width if you want to avoid considering order of media query declarations in your style-sheet

@media screen and (min-width: 320px) and (max-width: 640px) {
    .header-text {
       background-color: blue;
    }
}
15
votes

Include the meta bellow into the HTML which loads your iframe and it should work, at least on android devices.

<meta name="viewport" content="width=device-width, initial-scale=1">
8
votes

I ended up having to target the iframes width. (May not work in all situations)
But what i did was make the iframe 100% width and then it would resize with the window, so all i did was target the px of the iframe instead of the window

0
votes

A similar issue i had, where media queries were not working as expected, was the empty src value on the iframe.

I had a sandboxed iframe to preview email templates inside another page. I used javascript injection to fill the iframe's html content after getting the html data with an ajax call to a service.

The solution for me was to create an empty html file, set this to the iframe src and then update the content with javascript.

Code on my page:

<iframe src="/myfolder/dummy.html"></iframe>

Code for the iframe src:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="description" content="corrects media queries fails of email template previews" />
  <title></title>
</head>

<body>

</body>

</html>