JQuery and margin: 0 auto

So, this is the problem that was asked earlier, but I hope that we can put it to rest: I use jQuery 1.4. If I define a style

#obj { margin: 0 auto; } 

and then do

 $('#obj').css('marginLeft'); 

the result is the calculated value in pixels. Is there a way to find out if these pixels come from the auto calculation or not, indiscriminately document.styleSheets ?

+4
source share
2 answers

This solution will also work if the fields are set as a percentage, but it may be enough for your purposes. Basically, you record which fields change when you resize. Thus, you must write the fields before resizing to the array:

 var aMargins = []; $('.yourObjs').each(function(i,obj){ var objML = $(obj).css('marginLeft'); aMargins.push(objML); }); 

Then resize the window, see which fields have changed (it will be either β€œauto” or%), do what you need to do, and return it to its original size:

 var wW = $(window).width(); var wH = $(window).height(); window.resizeTo(wW - 5, wH); $('.yourObjs').each(function(i,obj){ if ($(obj).css('marginLeft') != aMargins[i]) { // your centering code here } } window.resizeTo(wW,wH); 

If your centering code just adjusts the left margin, then this should work fine for percent fields too. I can’t check this code or give an example, because I’m on the road and writing from the phone, but I hope this works or helps you come up with something that will happen.

+4
source

You cannot get auto from the element itself because styles cascade, what if you have it?

 #obj { margin: 0 auto; } div #obj { margin: 0 10px; } 

What is it? Depends on the page and how it is cascaded, the main idea is that you get the style properties calculated for this element, which does not matter in the style sheet, maybe 20 styles, etc.

This basically boils down to the following: getting auto vs 000px is a really rare request and will require a lot of extra code to understand, so much so that this is a simple case β€œno, it doesn’t belong to the kernel.” However, there are plugins for parsing CSS .

Short answer: the jQuery core cannot (does not have code) do this, jQuery with plugins or just JavaScript in general, yes you can.

0
source

Source: https://habr.com/ru/post/1312651/


All Articles