Search code examples
htmlcssiframe

CSS media query not working for elements within iframe


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


Solution

  • use

    iframe{
      widht:100%;
    }
    

    in your parent html