Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox computed margin auto returns 0

I have a div which is centred horizontally with css :

.bar {
    height: 38px;
    width: 970px;
    margin-left: auto;
    margin-right: auto;
}

I need to have another element to have same margin from the right as .bar, so I'm using jQuery sizes for this :

<div class="spec">I need to be aligned the same.</div>

JS:

$(".spec").css('margin-right', $('.bar').margin().right + 'px');

This works, but not in Firefox 30.0, as it returns 0 for computed margin-right of .bar. Any suggestions ? http://jsbin.com/difobu/1/edit.

$('.bar').css('margin-right') return 0px in FF 30.0 as well. If you donwnvote please provide an explanation.

like image 536
mishap Avatar asked Apr 18 '26 11:04

mishap


1 Answers

Unfortunately, this comes down to browser differences. To quote an answer to a similar problem:

As to why Chrome and IE return different values: .css() provides a unified gateway to the browsers' computed style functions, but it doesn't unify the way the browsers actually compute the style. It's not uncommon for browsers to decide such edge cases differently.

So you're kinda screwed. You have a few options to make this consistent.

You can reliably return auto by hiding the element before you compute the style. Something like this might work:

var $bar = $('.bar');
$bar.hide();
var barMarginRight = $('.bar').margin().right; // "auto"
// do whatever you need to do with this value
$bar.show();

You can also use jQuery's $('.bar').offset(), which returns properties you might be able to use.

// This might not be exactly what you want, but...
$('.spec').css('margin-left', $('.bar').offset().left + 'px');

You can also try to fix the problem with CSS, though we'd need to see your whole page to decide about that.

like image 101
Evan Hahn Avatar answered Apr 20 '26 01:04

Evan Hahn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!