With jQuery.css() I've been told I can use the following two functions for the same results:
$(".element").css("marginLeft") = "200px";
$(".element").css("margin-left") = "200px";
I've always used marginLeft
as this is what is used in the documentation:
Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.
Why has jQuery allowed for marginLeft
as well as margin-left
? It seems pointless and uses more resources to be converted to the CSS margin-left
?
when is marginLeft being used:
$("div").css({ marginLeft:'12px', backgroundPosition:'10px -10px', minHeight: '40px' });
As you can see, attributes that has a hyphen on it are converted to camelcased format. Using the margin-left
from the previous code block above would make JavaScript bonkers because it will treat the hyphen as an operation for subtraction.
when is margin-left used:
$("div").css("margin-left","12px").css("background-position","10px -10px").css("min-height","40px");
Theoretically, both code blocks will do the same thing. We can allow hyphens on the second block because it is a string value while compared to the first block, it is somewhat an object.
Now that should make sense.
I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...
$(".element").css( { marginLeft : "200px", marginRight : "200px" } );
as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...
$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );
without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.
EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];
Late to answer, but no-one has specified that css property with dash won't work in object declaration in jquery:
.css({margin-left:'200px'});//won't work
.css({marginLeft:'200px'});//works
So, do not forget to use quotes if you prefer to use dash style property in jquery code.
.css({'margin-left':'200px'});//works
jQuery is simply supporting the way CSS is written.
Also, it ensures that no matter how a browser returns a value, it will be understood
jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor').
Hi i tried this it is working.
$("#change_align").css({"margin-top":"-39px","margin-right":"0px","margin-bottom":"0px","margin-left":"719px"});
Source: Stackoverflow.com