jQuery css()

jQuery css() method can either be used to set a specified CSS property ( where it set the CSS property for ALL matched elements) or can be used to return the value of a specified CSS property ( where it return the CSS property value of the FIRST matched element).

jQuery css() sets or returns the CSS properties for the selected elements.

Syntax:

When it is used to return the value.

css("propertyname")

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
    	alert("Background color = " + $("p").css("background-color"));
	});
});
</script>
</head>
<body>
 
 
<p style="background-color:yellow">How are you?</p>
 
 
<p>How are you?</p>
 
<button>Click me to know my color.</button>
</body>
</html>

Try it

JS Bin on jsbin.com
When it is used to set a specified CSS property.

css("propertyname","value");

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
    	$("p").css("background-color", "cyan");
	});
});
</script>
</head>
<body>
 
<h2>Hello!</h2>
 
<p style="background-color:pink">How are you?</p>
<p style="background-color:yellow">How are you?</p>
<p>How are you?</p>
 
<button>Click me for a change</button>
 
</body>
</html>

Try it

JS Bin on jsbin.com
 

When it is used to set multiple CSS properties.

css({"propertyname":"value","propertyname":"value",...});

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
    	$("p").css({"background-color": "cyan", "font-size": "250%"});
	});
});
</script>
</head>
<body>
 
<h2>Hello</h2>
 
<p style="background-color:red">How are you?</p>
<p style="background-color:yellow">How are you?</p>
<p style="background-color:blue">How are you?</p>
 
<p>How are you?</p>
 
<button>Click me for multiple changes.</button>
 
</body>
</html>

Try it

JS Bin on jsbin.com

Please Share