jQuery css()

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

Below the syntax of jquery val() method

Return the CSS property value:

.css(property);

Set the CSS property and value:

.css(property, value);

Set CSS property and value using a function:

.css(property, function (index, currentvalue));

Set multiple properties and values:

.css({property:value, property:value, ...});

Return a CSS property

It is used to get the value of a specified CSS property.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery css()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $("#button").click(function() {
     alert("Font Size is : " + $("p").css("font-size"));
  });
});
</script>
</head>
<body>
 <p style="font-size:18px">lorem ipsum dolor sit</p>
 <button style="margin:0 0 10px 0" class="btn" id="button">Click here to get a font size of first matched element</button><br />
 </body>
</html>

Set a CSS property

It is used to set a specific value for all matched element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery css()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<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("font-size", "20px");
  });
});
</script>
</head>
<body>
 <p>This is first paragraph</p>
 <p>This is another paragraph</p>
 <button style="margin:0 0 10px 0;background:#e8e8e8;" class="btn" id="button">Click here to set a specific value for all matched elementt</button><br />
 </body>
</html>

Set multiple CSS properties

It is used to add multiple property values together.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery css()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<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({"font-size":"20px", "color":"#ff0000"});
  });
});
</script>
</head>
<body>
 <p>This is first paragraph</p>
 <p>This is another paragraph</p>
 <button style="margin:0 0 10px 0" class="btn" id="button">Click here to add multiple property values</button><br />
 </body>
</html>