3

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.

mishap
  • 8,176
  • 14
  • 61
  • 92
  • 1
    Have you tried `$('.bar').css('margin-right')`? – j08691 Jun 18 '14 at 17:35
  • 1
    Seriously, `$('.bar').margin().right` works in other browsers? It should be `$('.bar').css('margin-right')` – adeneo Jun 18 '14 at 17:36
  • $('.bar').css('margin-right') returns 0 in FF, but returns a number in Chrome. – mishap Jun 18 '14 at 17:39
  • Please show the relevant HTML markup. Is `.bar` nested inside of another element? What value are the other browser's returning? – War10ck Jun 18 '14 at 17:49
  • Not to be rude, but what's the point of that plugin? It seems like it does all the same functionality as `.css()` with the additional overhead of an added function call. Am I missing something? – War10ck Jun 18 '14 at 17:51
  • http://jsbin.com/difobu/1/edit – mishap Jun 18 '14 at 18:04
  • @War10ck, you are right, there is no need for the library, but I get the same result when using .css() – mishap Jun 18 '14 at 18:17

1 Answers1

9

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.

Community
  • 1
  • 1
Evan Hahn
  • 12,147
  • 9
  • 41
  • 59