Here in this guide, we have explained this method in detail, moreover, we have demonstrated different examples that help you better understand the method and its usage.
css() Method
The css() method in jQuery is used for the purpose of either fetching or applying one or more style properties to an HTML element.
Syntax
To apply a CSS property.
To fetch a CSS property.
To apply multiple CSS properties.
To better understand the css() method, let’s explore some examples.
Example 1: How to set a CSS property
Suppose you want to set the background color of a <h1>element using the css() method in jQuery.
HTML
<br><button class="button">Set background-color of h1</button>
In the above HTML code, we have created an <h1>, and a <button>element.
jQuery
$(".button").click(function(){
$("h1").css("background-color", "yellow");
});
});
In the above jQuery code, we have applied a yellow background color to the <h1>element using the css() method.
Output
Before clicking the button.
After clicking the button.
The background color of the heading has been set successfully.
How to fetch a CSS property
Suppose you want to fetch any CSS property of an element, for instance, background color of a div element. Follow the code below.
HTML
<br><button>Return background-color of div</button>
Here we have created a <div>, and a <button>element.
jQuery
$("button").click(function(){
alert("Background color = " + $("div").css("background-color"));
});
});
In the above code, the css() method is used only to extract the background color assigned to the <div>element. Moreover, an alert message has been created that will display the background color of the div.
Output
The background color of the div element has been fetched and displayed successfully.
How to set multiple CSS properties
Suppose you want to assign multiple style properties to any HTML element all at once. Follow the example below.
HTML
<br><button>Set multiple styles</button>
In the above code, we have created a <p>element along with a <button>element.
jQuery
$("button").click(function(){
$("p").css({"background-color": "yellow", "padding": "25px", "width": "200px"});
});
});
Using the jQuery css() method we have applied a background color to the <p>element and assigned it some padding and width.
Output
It can be verified from the above output that multiple styles are applied to the paragraph all at once.
Conclusion
You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties. This tutorial guides you on how to change CSS in various ways through jQuery css() method along with the relevant examples for better understanding.