Search code examples
javascripthtmlcssmedia-queriesviewport

CSS element with 100% width falls outside of viewport


I have code here which determines the size of an advertisement to use based on the user's screen size. I also made it so that if the screen is too small, the ad is centered with an automatic margin.

When I ran the page with google page-speed insights, I get this message:

The page content is 421 CSS pixels wide, but the viewport is only 411 CSS pixels wide. The following elements fall outside the viewport:

The element Advertisement falls outside the viewport.

This suggests to me that somehow element Q has margins to the left and right of the element that total 10px, yet I never declared such margin for Q. The Ad unit in the test done by google is 320x100

HTML:

<div id="Q">
    Advertisement<br>
    <ins id="Z">
        <!-- adsense box -->
    </ins>
</div>

CSS:

@media screen and (max-width:450px){
    #Q{
        width:100%;
        margin:0
    }
    #Q,#Z{
        margin:auto;
        overflow:hidden
    }
}
#Q{
    float:left;
    margin:10px
}
#Z{
    display:block;
    width:234px;
    height:60px
}
@media screen and (min-width:319px){
    #Z{
        width:320px;
        height:100px
    }
}
@media screen and (min-width:470px){
    #Z{
        width:300px;
        height:250px
    }
}

I have configured the viewport using the following code:

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

This is the page that was tested in various resolutions on a desktop browser without problems, which generated the page-speed insights issue above.

http://new.clubcatcher.com/m/pictures/bloke/2016apr02/1

Is there anything in my CSS that could be causing this issue? What can I do to fix it?


Solution

  • The clue is in the name. CSS stands for Cascading Style Sheets, so any CSS that has the same specificity will always be overridden by the last CSS rule in your CSS stack. The two classes in your CSS after the first media query will apply at all media sizes, since you aren't specifying one for those two, and since they come after the first ones, they will take precedence.