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:
<!DOCTYPE html>
<html>
<head>
<title>jQuery css Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Make Background Yellow</button>
<script>
$("button").click(function(){
$("p").css("background-color", "yellow"); // Change background color of all paragraphs
});
</script>
</body>
</html>
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.
$(selector).css({
"propertyName1": "value1",
"propertyName2": "value2",
// ... more properties
});
Example
The following example sets both the background color and font size for
all <p> elements:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Multiple CSS Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Apply Multiple Styles</button>
<script>
$("button").click(function(){
$("p").css({
"background-color": "yellow",
"font-size": "200%"
});
});
</script>
</body>
</html>
This approach is ideal when you want to style elements with multiple
properties in a single method call.
More topic in jQuery