jQuery css Method

The css() method lets you read and write CSS properties directly from JavaScript. It is great for one-off style tweaks or values you have to calculate at runtime, when creating a dedicated class would be overkill.

The css() method

css() is flexible. With one property name it reads the current value. With a property and a value it sets that style. With an object it sets several styles at once. This makes it a Swiss Army knife for inline styling.

  • css('property') - returns the current value of a single property.
  • css('property', 'value') - sets a single property.
  • css({property: value, ...}) - sets multiple properties in one call.

Read a CSS value

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<p style="background-color: lightblue;">This is a paragraph.</p>

<script>
// Get the current background color of the first paragraph
var color = $("p").css("background-color");
console.log(color);
</script>

</body>
</html>

Set a single property

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box">This is the box.</div>

<script>
$("#box").css("background-color", "lightblue");
</script>

</body>
</html>

Set several properties at once

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box">This is the box.</div>

<script>
$("#box").css({
  "background-color": "lightblue",
  "font-size": "18px",
  "padding": "10px"
});
</script>

</body>
</html>
Call styleExampleWhat it does
Getcss('color')Returns the value of the property
Set onecss('color', 'red')Sets a single property
Set manycss({...})Sets multiple properties together
Note: When reading a value, css() returns the computed style, so a color often comes back as an rgb() string even if you set it with a name like 'red'.
Note: For styles you use in more than one place, prefer addClass() over css(). Keeping styles in your CSS file is easier to maintain than scattering inline values through your scripts.

Exercise: jQuery css() Method

How do you read the current computed value of a single CSS property with jQuery?