Set Multiple CSS Properties with jQuery
Applying several style rules to HTML elements at once is a common
task in web development. In jQuery, you can set multiple CSS properties
simultaneously by passing a JavaScript object containing key-value pairs
directly into the .css() method. This approach updates all
target properties in a single statement, streamlining your code and
reducing unnecessary DOM manipulations.
The Syntax
To define multiple CSS styles, pass an object literal {}
as the argument to jQuery's .css() method.
$(selector).css({
"property-name": "value",
"property-name": "value"
});Property Naming Conventions
When writing CSS property names inside the object, you can use either standard hyphenated CSS property names or camelCase format:
- Quoted Hyphenated Strings: If you use standard CSS names containing hyphens, you must wrap the property names in quotes.
- Unquoted CamelCase: If you use camelCase, quotes are optional for the property names.
Example
The following code demonstrates both naming conventions applied to an
element with the ID #box:
$("#box").css({
backgroundColor: "#f4f4f4", // camelCase, no quotes needed for property
"font-size": "18px", // standard CSS, requires quotes
color: "#333333",
padding: "20px",
"border-radius": "8px"
});Relative and Dynamic Values
jQuery allows you to use relative values (such as += or
-=) to adjust styles relative to their current values:
$(".card").css({
width: "+=50px",
height: "+=20px",
opacity: 0.8
});Using an object with the .css() method is cleaner, more
readable, and faster than chaining multiple individual
.css() calls, making it the standard best practice for
multi-property manipulation in jQuery.