tags:

views:

9053

answers:

8

Is there any syntactical way in JQuery to define multiple CSS attributes without stringing everything out to the right like this:

$("#message").css("width", "550px").css("height", "300px").css("font-size", "8pt");

If you have, say, 20 of these your code will become hard to read, any solutions?

+22  A: 

better to just use .addClass even if you have 1 or more. More maintainable and readable.

If you really have the urge to do multiple css props then use

.css( {width : '30px', height : '10px'} )

redsquare
Also allows for better separation of code.
Brian Fisher
as in More maintainable and readable :)
redsquare
+5  A: 
$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });
Jimmy
to get that to work you have to change some syntax on it: $('#message').css({ width : '550px', height : '300px', 'font-size' : '8pt' });
Edward Tanguay
erm, thanks to all the drive-by downvoters who never read jquery documentation? numeric values are converted into pixel values automatically kthx.
Jimmy
Yea what's the problem here? `width: 550` is perfectly valid.
thenduks
+6  A: 

pass it a json object:

$(....).css({
    'property': 'value', 
    'property': 'value'
});

http://docs.jquery.com/CSS/css#properties

dave mankoff
+2  A: 

From jQuery:

$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
Jonathan Sampson
+1  A: 

Agree with redsquare however it is worth mentioning that if you have a two word property like text-align you would do this:

$("#message").css({ width: '30px', height: '10px', 'text-align': 'center'});
Darko Z
A: 

ok, but what would I do when I have to put a VAR as a CSS value?

like this:

var divHeight = $('div').height();) $('div.another').css('height', divHeight + 40, 'line-height': divHeight);

Could someone help?

Link
$("#message").css({ width: <var1>, height: <var2>}); etc.
futureelite7
Firstly, please don't post answers that ask questions, make a new question for that. Secondly: `$('div.another').css( { height: divHeight + 40, ... } );`
thenduks
A: 

could do something like this perhaps:

var lineHeight = $('div').height();

var divHeight = lineHeight + 40;

$('div.another').css( { 'height': divHeight, 'line-height': lineHeight } );

timothyclifford
A: 

$("p:first").css("background-color", "#B2E0FF").css("border", "3px solid red");

Sumith Harshan