9

I'm looking for an easy way to locate elements on the page that have margin-left and margin-right set to auto.

I got this script, that helps me some of the time:

(function() {
  var elementsList = [];
  for (var i = 0; i < document.styleSheets.length; i++) {
    var styleSheet = document.styleSheets[i];
    if (styleSheet.rules) {
      for (var j = 0; j < styleSheet.rules.length; j++) {
        var rule = styleSheet.rules[j];
        if (rule && rule.style && rule.style.marginLeft == 'auto' && rule.style.marginRight == 'auto') {
          var smallList = document.querySelectorAll(rule.selectorText);
          if (smallList.length)
            elementsList = elementsList.concat(smallList);

        }

      }
    }
  }
  return elementsList
})();

While this function gets some of the job done, it doesn't catch most cases of margin: auto I've seen in websites.

Can you show me a better way?

5
  • There is an easier way. Why do not you create a class? Something like .margin-auto and search by all these elements? Commented Nov 12, 2014 at 10:31
  • This sounds like a jQuery selector problem. Do you want that?
    – Paul
    Commented Nov 12, 2014 at 10:32
  • You will have it a lot easyer if you include jquery and simply use the selectors there. @MDeSchaepmeester TO BITE YOU ;)
    – Dwza
    Commented Nov 12, 2014 at 10:33
  • 3
    I think you should better go with getComputedStyles to reliably filter elements with margin-left/right equal to auto. Also document.styleSheets is smart but there is also a possibility of inline styles. That being said, the code is going to be pretty greedy as you need to scan many page elements. You can make it a little bit more efficient by skipping inline elements and elements like <br>.
    – dfsq
    Commented Nov 12, 2014 at 10:33
  • @dfsq Unfortunately this fails in FF and Safari, both returns 0px when margins are set to auto even when they render correctly centered. Commented Nov 13, 2014 at 15:40

4 Answers 4

2

If you're OK to use JQuery

As said by Martin Ernst for yonatan's answer: 'This will select only elements with marginLeft/Right="auto".'

Besides, as described in the comments, elements must be hidden in order to work with FF and safari.

This should work using JQuery:

$(document).ready(function() {
    var visibleElements = $('body *:visible');
    $('body *').hide();
    var elements = $('body *').filter(function() {
        return $(this).css('margin-left') == 'auto' && $(this).css('margin-right') == 'auto';
    })
    // show only elements that were visible
    visibleElements.show();
});

Tip: if for some reason, you need to not load external scripts, just copy the content of the minified jquery script at the begining of yours.

9
  • Unfortunately this fails in FF and Safari, both returns 0px when margins are set to auto even when they render correctly centered. Commented Nov 13, 2014 at 15:38
  • Can you do all actions you want on the dom? If you can, call $('*').hide(); at the very beginning of your script. Doing this, the 'auto' value won't be calculated (well, I think so... ;) ). If it works, I'll update my answer.
    – Nicolas
    Commented Nov 13, 2014 at 15:56
  • Correct, but hide() should undo those calculations (I've ever done this kind of 'brachial' things ^^).
    – Nicolas
    Commented Nov 13, 2014 at 16:06
  • If I type this following code in the console, with this stackoverflow page displayed, I get elements with chrome and FF, don't you? $('*').hide();$('body *').filter(function() { return $(this).css('margin-left') == 'auto' && $(this).css('margin-right') == 'auto'; })
    – Nicolas
    Commented Nov 13, 2014 at 16:23
  • Yeah it works, I did it in the wrong script. Include it (in ($(document).ready and a show() afterwards), and I will upvote. Commented Nov 13, 2014 at 16:38
0

use jQuery:
$('*').filter(function(i, d){return d.style.marginLeft == "auto" && d.style.marginRight == 'auto';});

2
  • He'd better use $('body *'), this avoid looping into unecessary elements (head, meta, etc.). Commented Nov 12, 2014 at 13:02
  • This will select only elements with marginLeft/Right="auto" set in their style-attribute, but not those where it's set by CSS. Commented Nov 12, 2014 at 17:01
0

I hate to say this, but this one has less success then my own version.

1
  • Your problem is not trivial. Did you try Nicolas answer ? It should work except in Safari. Commented Nov 13, 2014 at 18:21
0

This problem is not trivial. Even in the days of window.getComputedStyle() it's hard to get a crossbrowser reliable answer for marginLeft/Right when margins are set to auto. So this is shurely not a complete answer but will try helping to find one.

margin-left and margin-right are also auto when the margin-shorthand is used:

#elem {margin: auto;} // or:
#elem {margin: 100px auto;} // or:
#elem {margin: 100px auto 30px;} // or:
#elem {margin: 100px auto 30px auto;}

You have to find those notations too when you are searching in the stylesheets. Include this function just before var elementsList=[]; in your code:

function expand(margin) {
    var parts = margin.split(' ');
    for (var i = 3; i; i--) parts[i] = parts[i] || parts[i - 2] || parts[0];
    return parts[1] == 'auto' && parts[3] == 'auto';
}

Then change your inner if-condition to:

if (rule && rule.style &&
    (rule.style.marginLeft == 'auto' && rule.style.marginRight == 'auto' || expand(rule.style.margin))
) {
    var smallList = document.querySelectorAll(rule.selectorText);
    if (smallList.length) elementsList = elementsList.concat(smallList);
}

Now you get also the rules where margin is used. But some problems stay with your code:

  • Same elements may be listed multiple times when they match more than one rule
  • It's not shure that all listet elements are really rendered with marginLeft/Right = auto. Maybe that css becomes overridden by another more specific rule.
  • As dfsq mentioned in his comment there can be inline-styles you can't find this way.
1
  • I acctually don't care much about cross-browser compatibility. I want to create an addon to any browser, that will detect the margin auto elements (and do stuff, you need to know about :))
    – GuruYaya
    Commented Nov 16, 2014 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.