Search code examples
cssmedia-queries

cannot hide div out of viewport


I want to hide my absolute positioned div out of viewport when viewport is less than 960px. Here's the css for div and media query with rule of hiding:

@media all and (max-width: 960px) {
    .newsbox{
        right:-355px;
    }

}  

.newsbox{
    position:fixed;
    right:0;
    top:0;
    height:100%;
    background:#fff;
    z-index:900;
    width:395px;
    overflow:hidden;
    background:#f7f7f7;
}

Can anybody explain me why this rule is not hiding this element when browser window is not wider than 960px? Thanks in advance!


Solution

  • Your @media rule needs to be placed below, otherwise the cascade will cause your outer .newsbox rule to always take precedence and override the right style in your inner .newsbox rule, regardless of whether your media query is in effect:

    .newsbox {
        position: fixed;
        right: 0;
        top: 0;
        height: 100%;
        background: #fff;
        z-index: 900;
        width: 395px;
        overflow: hidden;
        background: #f7f7f7;
    }
    
    @media all and (max-width: 960px) {
        .newsbox {
            right: -355px;
        }
    }