Search code examples
cssmedia-queriescss-position

Media query ignores position:fixed


I've looked everywhere for a solution to this and can't believe the answer has eluded me so far. My appearance here is a last resort. Hope you don't mind me picking your brains.

In a website I am building I am trying to position a graphic at the top right of the screen. Then when the window is narrowed to 760px or less, I want it to move to the bottom. No matter what I do the thing just will not move to the bottom. It stays at the top. Here is some very simple code, and it doesn't work here either:

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
    <link rel="stylesheet" type="text/css" href="css.css" id="theme_color">
</head>

<body>

<div class="mydiv">HELLO!</div>

</body>
</html>

and the CSS:

@charset "utf-8";
/* CSS Document */

.mydiv { 
    position:fixed;
    top:0;
    right:0;
}

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

.mydiv { 
    bottom:0;
}
}

That's all the code there is. You cab see that the word 'hello' appears top right. But when you make the browser window narrow, instead of moving to the bottom as I want, it stays at the top.

BUT... if alter the CSS, so that the div starts at the bottom (wide screen) and moves to the top on narrowing, it works as it should:

.mydiv { 
    position:fixed;
    bottom:0;
    right:0;
}

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

.mydiv { 
    top:0;
}
}

Totally stumped. Ideas? Tried Chrome, FF and IE, all latest versions. Windows 7.

Thanks.

Mark


Solution

  • That's because top has more precedence that bottom so the value of bottom is being ignored:

    When both top and bottom are specified, as long as height is unspecified, auto or 100%, both top and bottom distances will be respected. Otherwise, if height is constrained in any way, the top property takes precedence and the bottom property is ignored.

    So you need to set the top to auto, try this:

    @media only screen and (max-width: 760px) {
    
    .mydiv { 
        bottom:0;
        top:auto;
    }
    }
    

    Check this Demo http://jsfiddle.net/brsrmq4v/