Using the jQuery css() method, you can set or return the one or more style properties for the selected elements.
Here are the two ways to provide jQuery css() method:
1 2 3 4 |
Set a CSS property urn a CSS property |
Set a CSS property
Using the set property of CSS, you can set a specific value for all matched elements.
Syntax:
1 2 3 |
css("propertyname","value"); |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css("background-color", "orange"); }); }); </script> </head> <body> <h2>Heading 1</h2> <p style="background-color:#0000ff">This is the first paragraph.</p> <p style="background-color:#ff0000">This is the second paragraph.</p> <p style="background-color:#00ff00">This is the another paragraph.</p> <p>This is the main paragraph.</p> <button>Set background-color of p</button> </body> </html> |
Return a CSS property
It is used to return the value of a specified CSS property.
Syntax:
1 2 3 |
css("propertyname"); |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ alert("Background color = " + $("p").css("background-color")); }); }); </script> </head> <body> <h2>Heading 1</h2> <p style="background-color:#ff0000">This is the first paragraph.</p> <p style="background-color:#00ff00">This is second paragraph.</p> <p style="background-color:#0000ff">This is last paragraph.</p> <button>Return background-color of p</button> </body> </html> |
Set Multiple CSS Properties
It is used to set multiple CSS properties.
Syntax:
1 2 3 |
css({"propertyname":"value","propertyname":"value",...}); |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").css({"background-color": "orange", "font-size": "200%"}); }); }); </script> </head> <body> <h2>This is a heading</h2> <p style="background-color:#ff0000">This is a paragraph.</p> <p style="background-color:#00ff00">This is a paragraph.</p> <p style="background-color:#0000ff">This is a paragraph.</p> <button>Set multiple styles for p</button> </body> </html> |