jQuery css()

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

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 :

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 = #exPid
  var cssPropValue = $("#exPid").css("color");
  // displaying the value in p#exOutput
  $("#exOutput").text(cssPropValue);
});
</script>
</head>
<body>

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

<p id="exOutput"></p>

</body>
</html>
Try Online

Output

Learning jQuery css().

rgb(0, 170, 0)

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 = #exPid
  var cssPropValue = $("p#exPid").css("color", "blue");
  var cssPropValue = $("p#exPid").css("border", "1px solid grey");
 });
</script>
</head>
<body>

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

</body>
</html>
Try Online

Output

Learning jQuery css().

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#exPid").css("color", "blue").css("border", "1px solid #CCC").css("border-radius", "4px").css("padding", "5px");
 });
</script>
</head>
<body>

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

</body>
</html>
Try Online

Output

Learning jQuery css().

Conclusion

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