1

Below is an example of how I currently would affect two css properties for the same div in jquery:

$('#mydiv').css("width",myvar+"px");
$('#mydiv').css("margin-left",myvar+"px");

I don't believe this to be the most efficient method as it requires two lines of code for one div, can somebody please show me a more susinct (tidier) method of writing the same thing?

1
  • 2
    If myvar is a constant, then you can just add a class to myDiv and define the css in your stylesheet Commented Apr 2, 2014 at 14:11

3 Answers 3

3

.css( properties )

properties Type: PlainObject An object of property-value pairs to set.

$('#mydiv').css({
    "width": myvar + "px",
    "margin-left": myvar + "px"
});

Or you can add class to the element.

Sign up to request clarification or add additional context in comments.

5 Comments

+ "px" is not necessary, jQuery will assume it's pixels if you don't specify it
@JonasGrumann: Amusingly, I was just checking the docs to see if that was the case, because someone else mentioned it a couple of months back, and came back and saw your comment. I don't see that anywhere in the docs, is it documented behavior?
Wrong place in doc. Look down at .css(properties). It says: properties Type: PlainObject An object of property-value pairs to set.
I think I've read it in some version's changelog, not really the doc. I guess they didn't mention it to avoid confusion. In the annotated source robflaherty.github.io/jquery-annotated-source/docs/11-css.html you can see if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; }
@T.J.Crowder They talk about it in animate() relative DOC, regarding object of CSS properties: Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.. I hope this is relevant here too
0

You can pass an object instead:

$('#mydiv').css(
  { 
    'width': myvar + 'px',
    'margin-left': myvar + 'px'
  }
);

Comments

0

You can use this syntax (css properties). Personally I prefer to use the javascript property syntax

$('#mydiv').css({
    width: myvar,
    marginLeft:  myvar
});

Edit: per the comment made on Tushar Gupta's answer, I've removed the + 'px'. Apparently you don't need that at least with the latest jQuery build. http://jsfiddle.net/75cMM/

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.