jQuery css

The jQuery css() method is applied on an html element. It is used to get or set the value of one or more style properties of the html element.

In this tutorial, you will learn about jQuery css() method, its syntax and usage, with examples.

Syntax jQuery css

Following is the syntax to use css() method

Get CSS Property Value

To get the value of specified CSS property corresponding to the HTML Element,

$("htmlElement").css("css_property");

Set CSS Property Value

To set the value of specified CSS property corresponding to the HTML Element,

$("htmlElement").css("css_property", "value");

Examples jQuery css

Following examples help you understand the usage of jQuery css() method :

1 Example Get value of css property

In the following jQuery css() example, we shall get value of css property of an HTML Element to a variable, and write it to a paragraph element.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // get value of css property : color of <p> with id = #my_id
  var cssPropValue = $("#my_id").css("color");
  // displaying the value in p#output
  $("#output").text(cssPropValue);
});
</script>
</head>
<body>

<p id="my_id" style="color:rgb(0, 170, 0)">Learning jQuery css().</p>

<p id="output"></p>

</body>
</html>

2 Example Set value to css property

In the following jQuery css() example, we shall set value of css property for an HTML Element.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
  // set value of css property : color for <p> with id = #my_id
  var cssPropValue = $("p#my_id").css("color", "blue");
  var cssPropValue = $("p#my_id").css("border", "1px solid grey");
 });
</script>
</head>
<body>

	<p id="my_id">Learning jQuery css().</p>

</body>
</html>

3 Example Set values to multiple css properties in a single line

Following jQuery css() example demonstrates how to set values to multiple css properties in a single statement using jQuery Method Chaining.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
 $(document).ready(function(){
  // set value of multiple css properties
  var cssPropValue = $("p#my_id").css("color", "blue").css("border", "1px solid #CCC").css("border-radius", "4px").css("padding", "5px");
 });
</script>
</head>
<body>

	<p id="my_id">Learning jQuery css().</p>

</body>
</html>

Conclusion

In this jQuery Tutorial, we have learnt jQuery css() method : Syntax and Usage with examples.