Reputation: 250
Hi I'm trying position new dom element same as old one, and then hide old one so new would replace it: http://jsfiddle.net/jC33F/5/
Though if original element has margin:auto jQuery can't retrieve it. Is there a way to be able to determine if element has margin:auto; ?
Edit: Thanks to @Vibhu I came up with this http://jsfiddle.net/jC33F/43/ looks horrible :D And I'm not sure it will always work.
Feel free to suggest something better.
Upvotes: 5
Views: 2403
Reputation: 5199
I didn't like any of these solutions. Checking the actual stylesheet is a solution. Another solution I came up with is to store the left/right values, temporarily change the left value and see if the right value still matches. If not, then it is set to auto.
var mLeft = el.css('margin-left');
var mRight = el.css('margin-Right');
el.css('margin-left',(parseInt(mLeft)-2)+'px');
var mRightChanged = el.css('margin-Right');
if (mRight != mRightChanged) {
console.log('read element left/right margins as auto');
el.css('margin-left','auto');
} else {
console.log('read element left/right margins as their value');
el.css('margin-left',mLeft);
}
Note, this solution is just for left/right margins.
Upvotes: 0
Reputation: 3695
This might be crazy, but what about something like this for checking it an element has margin: 0 auto
(cannot seem to find any other way):
var margin = $("#parent").css("margin");
if($('#parent').position().left*2 == ($('#parent').parent().innerWidth() - $('#parent').outerWidth())) {
margin = "0px auto";
}
$("#positionable").css({
position: $("#parent").css("position"),
top: $("#parent").css("top"),
left: $("#parent").css("left"),
margin: margin
});
$("#parent").hide();
This code basically checks if the left value of #parent is equal to half the space between the 2 edges of its container. Worked for me in this case, might fail in other cases.
Upvotes: 2
Reputation: 9858
Check if the returned margin is empty would work I guess
Be aware though, that if you do not set any margin property, this will still set #positionable
margin property to auto
EDIT:
I found this jQuery plugin that claims it can return the margin property from an element
http://www.bramstein.com/projects/jsizes/
Upvotes: 0
Reputation: 16167
Try it with position absolute for #positionable
$("#positionable").css({
position: 'absolute',
top: $("#parent").position().top,
left: $("#parent").position().left,
margin: $("#parent").css("margin"),
});
Upvotes: 0