Categories
JavaScript Tips & Tutorials jQuery Tips & FAQ

How to define multiple CSS rules / properties in jQuery?

The simplest way to define a CSS rule in jQuery might be:

$(".sth").css("color", "#f00");

To define more than one CSS rule in a single jQuery line:

$(".sth").css("color", "#f00").css("font-style", "italic").css("text-decoration", "underline");

Which simply doesn’t look that good, especially if you intend to add more. A better way to specify multiple CSS rules or properties with jQuery is by a JSON object:

$(".sth").css( {'color' : '#f00', 'font-style' : 'italic', 'text-decoration' : 'underline'} );

However, it is recommended that you use .addClass() instead of .css() to separate the JavaScript logics and CSS styles for maintainability.

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Kavoir.com? Shoot me a message.