jQuery CSS() Method

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:

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:
css("propertyname","value");

Example:

<!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>
Try Now

Return a CSS property

It is used to return the value of a specified CSS property. Syntax:
css("propertyname");

Example:

<!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>
Try Now

Set Multiple CSS Properties

It is used to set multiple CSS properties. Syntax:
css({"propertyname":"value","propertyname":"value",...});

Example:

<!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>
Try Now



ADVERTISEMENT
ADVERTISEMENT