jQuery css() Method
The css() method in jQuery is used to get or set one or more CSS properties of selected elements.
Retrieving a CSS Property
To get the value of a specific CSS property from the first matched element, use the following syntax:
$(selector).css("propertyName");
Example
The following code retrieves the background color of the first <p> element on the page:
$("p").css("background-color");
This is helpful when you need to read styling information directly from an element.
Setting a CSS Property
You can use the css() method to assign a specific style to one or more elements. The syntax for setting a single property is:
$(selector).css("propertyName", "value");
Example
The following code sets the background color of all <p> elements to yellow:
$("p").css("background-color", "yellow");
This method is great for applying styles dynamically without needing to add or modify CSS classes.
Setting Multiple CSS Properties
jQuery also allows you to set multiple CSS properties at once using an object literal. This makes the code cleaner and more efficient when applying several styles to the same elements.
Syntax
$(selector).css({
"propertyName1": "value1",
"propertyName2": "value2",
// ... more properties
});
Example
The following example sets both the background color and font size for all <p> elements:
$("p").css({
"background-color": "yellow",
"font-size": "200%"
});
This approach is ideal when you want to style elements with multiple properties in a single method call.