jQuery CSS

jQuery CSS() Method

The css() method sets or returns one or more style properties for the selected elements.

1. Get a CSS Property

This is used to return the value of a specified CSS property, use the following syntax.

css("propertyname");

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
});
</script>
</head>
<body>
<h2>CSS Property</h2>
<p style="background-color:red">This is a paragraph.</p>
<p style="background-color:yellow">This is a paragraph.</p>
<p style="background-color:blue">This is a paragraph.</p>
<button>Get background-color of P</button>
</body>
</html>

Output

jquery CSS method

Now click on Get background-color of P button to get the value of a specified CSS property.

jquery CSS method

2. Set a CSS Property

This is used to Set the value of a specified CSS property, use the following syntax.

css("propertyname","value");

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").css("background-color", "yellow");
});
});
</script>
</head>
<body>
<h2>CSS Property</h2>
<p style="background-color:red">This is a paragraph.</p>
<p style="background-color:yellow">This is a paragraph.</p>
<p style="background-color:blue">This is a paragraph.</p>
<button>Set background-color of P</button>
</body>
</html>

Output

jquery CSS method

Now click on Set background-color of P button to set the value of a specified CSS property.

jquery CSS method

3. Set Multiple CSS Properties

This is used to set multiple CSS properties, use the following syntax.

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

The following example will set a background-color and a font-size for all matched elements.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").css({ "background-color": "yellow", "font-size": "50px" });
});
});
</script>
</head>
<body>
<h2>CSS Property</h2>
<p style="background-color:red">paragraph1</p>
<p style="background-color:yellow">paragraph2</p>
<p style="background-color:blue">paragraph3</p>
<button>Set Multiple CSS Properties</button>
</body>
</html>

Output

jquery CSS method

Now click on Set Multiple CSS Properties button to set multiple CSS properties.

jquery CSS method
Prev Next