jQuery css()

jQuery css() Method

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

While adding and removing classes is cleaner, sometimes you need to dynamically calculate exact pixel values or colors.


Getting a CSS Property

To return the value of a specified CSS property, use this syntax: css("propertyname");

This will read the computed style directly from the first matched element.

Get CSS Property:

$("button").click(function(){
  alert("Background color = " + $("p").css("background-color"));
});

Setting a Single CSS Property

To set a specified CSS property, you pass both the property name and the new value.

Syntax: css("propertyname", "value");

This will apply the style to ALL matched elements on the page.

Set Single Property:

$("button").click(function(){
  $("p").css("background-color", "yellow");
});

Setting Multiple CSS Properties

To set multiple CSS properties at the exact same time, you pass a JSON object.

Syntax: css({"propertyname":"value", "propertyname":"value", ...});

Set Multiple Properties:

$("button").click(function(){
  $("p").css({
    "background-color": "yellow", 
    "font-size": "200%"
  });
});

Exercise 1 of 2

?

If you call the css() method with only one parameter (the property name), what does it do?

Exercise 2 of 2

?

What format must you use to pass multiple CSS properties into the css() method at once?