jQuery Introduction | Setting CSS Styles and Properties | Setting CSS Styles .css()

Setting CSS Styles

With jQuery, you can easily retrieve or set property values related to the style of a selected element.

Method Description
.css() The css() method returns the style property value of the first element in the selected set, or sets the style property of the selected element to the value passed as an argument.

.css() Method

In jQuery, you can use the .css() method to easily set CSS styles on selected elements. The .css() method returns the style property value of the first element in the selected set, or sets the style property of the selected element to the value passed as an argument.

Setting a Style

$("p").css("backgroundColor", "#00ff00")

In the example above, the .css() method sets the background color of all <p> elements to #00ff00.

Run code

Returning a Style

$("p").css("backgroundColor")

In the example above, the .css() method returns the background color of the first <p> element.

Run code

Setting Multiple Styles at Once

With the .css() method, you can also set multiple property values related to the style of a selected element at once.

$("p").css({
  "fontSize": "30px",
  "backgroundColor": "yellow"
});

This sets the font size of all <p> elements to 30px and the background color to yellow.

Run code

Property Name Format

In JavaScript, when using CSS property names connected with hyphens (-), you must remove the hyphen and convert the name to camelCase.

However, jQuery’s .css() method can use both hyphenated CSS property names and camelCase property names.

  $("p").css({
    "fontSize": "30px",
    "color": "#ffffff",
    "background-color": "green"
  });

fontSize can be used in both JavaScript and jQuery, but background-color can be used only in jQuery.

Run code