简体   繁体   中英

Different values for jQuery.css('top-margin') with margin:auto based on browser

Let me try to lay this out, my question is why don't all the browsers treat this the same way.

html

<body>
    <div id="container"></div>
    <div id="footer"></div>
</body>

Css

body{
    height:100%;
    width:100%;
    position:relative;
}
.container{
    height:800px;
    width:800px;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin: auto;
}
.footer{
    position:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

jQuery

var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
$('#footer').css('top',footertop);

I have a container div that is absolutely centered horizontally and vertically. Then I am attempting to set the 'top' of the footer to be the height of container plus the top margin of container. (So that it ends up right underneath the container). This method works on some browsers (Chrome,Opera,Safari,IE9+) but doesn't work on others (Firefox,IE8-).

I am assuming IE8 and earlier doesn't support this method, and that's fine, but in Firefox the value of footertop is always equal to $('#container').css('height')

If I do a console.log(parseFloat($('#container').css('margin-top'))) I get a positive integer depending on the height of my browser, but on Firefox it is always 0.

Please advise.

Turns out in firefox the computed value for margin-top, margin-bottom, margin-left and margin-right all end up as 0 and the top,bottom,left and right attributes have the values that you would expect to find in the margins.

here is my jquery that works on all browsers now:

if(parseFloat($('#container').css('margin-top')) == 0){
    var footertop = (parseFloat($('#container').css('top'))+parseFloat($('#container').css('height')))+'px'; //firefox fix
}else{
    var footertop = (parseFloat($('#container').css('margin-top'))+parseFloat($('#container').css('height')))+'px';
}
$('#footer').css('top',footertop);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM