What Is the jQuery css() Method Used For?
This article explains the purpose, syntax, and primary applications
of the jQuery css() method. You will learn how to retrieve
computed CSS styles from HTML elements, set single style properties, and
apply multiple styles simultaneously using straightforward code
examples.
The jQuery css() method is an essential DOM manipulation
tool used to read or modify the style properties of selected elements.
It acts as both a getter and a setter depending on the parameters passed
to the function. When reading styles, it retrieves the computed style of
the first matched element; when setting styles, it applies inline CSS
styles to all matched elements in the selection.
Getting a CSS Property Value
To retrieve the current computed value of a style property, pass the property name as a single string argument.
// Returns the background color of the first matched paragraph
var bgColor = $("p").css("background-color");This returns the actual computed value as a string (such as
"rgb(255, 255, 0)"), regardless of whether the style was
applied via an external stylesheet, an internal
<style> block, or an inline attribute.
Setting a Single CSS Property
To set or change a single style rule, provide both the property name and the new value as separate string arguments.
// Sets the text color of all matched elements to red
$("p").css("color", "red");This directly injects the style into the element's style
attribute (e.g., <p style="color: red;">).
Setting Multiple CSS Properties
To apply several CSS rules at once, pass a JavaScript object containing key-value pairs representing the CSS properties and their respective values.
// Applies multiple styles simultaneously
$("p").css({
"background-color": "#f4f4f4",
"font-size": "16px",
"padding": "10px",
"border": "1px solid #ccc"
});Property names can be written either within quotes using standard CSS
hyphenated syntax (e.g., "background-color") or without
quotes using camelCase notation (e.g.,
backgroundColor).
Common Use Cases
- Dynamic Resizing: Adjusting widths, heights, or margins in response to window resize events or user input.
- Toggling Visibility: Changing properties like
displayoropacityto create custom animations or interface states. - Relative Adjustments: Using relative values such as
+=50pxor-=20pxto adjust existing dimensions programmatically.