Home > Software engineering >  CSS media query not working for elements within iframe
CSS media query not working for elements within iframe

Time:08-05

When I apply CSS media queries inside the iframe it is not affected. Below are my HTML files.

mainpage.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Sample Page</title>
    <style>
   
    @media screen and (max-width:767px) {
        p{
        color:lightblue;
        }
    }
    </style>
</head>
<body style="background-color: MediumSeaGreen;">
    <h1>My Sample Page Heading</h1>
    <p>My first paragraph.</p>
    <iframe src="iframe_sample.html" title="Sample IFrame to test" width="400px" height="500px"></iframe>
</body>
</html>

iframe_sample.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    body {
        background: #fff;
    }

    @media screen and (max-width:767px) {
        body {
            background: red;
        }
        p{
            color:lightblue;
        }
    }
</style>
</head>
<body>
    <h1>My iFrame Heading</h1>
    <p>My iFrame paragraph.</p>
</body>
</html>

Regardless of the screen size always iframe body background color is only red (which I set for mobile view). Also, the paragraph color inside the iframe also does not change according to the screen size.

I saw similar posts and added a viewport metatag also to the iframe. But cannot figure out what I am doing wrong.

Here are the screenshots.

Dektop View

Mobile View

CodePudding user response:

use

iframe{
  widht:100%;
}

in your parent html

CodePudding user response:

Look at the documentation for width (which you are using with the max- prefix):

The width CSS media feature can be used to test the width of the viewport (or the page box, for paged media).

It describes the width of the viewport not the screen.

It is almost never useful to adjust content based on the screen size. People look at webpages in viewports that don't take up the entire screen almost all the time. You're explicitly creating a viewport smaller than the whole screen using the iframe!

You might want to consider device-width, but it is deprecated and (for the reasons I mentioned above) not very useful.

  • Related