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?
The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
margin:auto won't work when you have a float or haven't specified a width. kohoutek: margin:auto won't work when you have a float or haven't specified a width.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With