English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery css() Method

jQuery HTML/CSS Methods

The css() method of jQuery gets or sets one or more style properties of the selected element.

when using the css() methodGetwhen setting the property value, it will returnthe first selected elementvalue.

Use the css() methodSetwhen setting the property value, it will beAll selected elementsSet one or more properties/value pair.

Similarly, jQuery can equally interpret multi-word CSS properties and DOM format. For example, jQuery can understand css(" background-color")and css(" backgroundColor") and return the correct value.

However, it does not fully support shorthand CSS properties (such as "background", "margin", and "border") and may produce different results in different browsers.

Syntax:

Get CSS property value:

$.css(property)

Set CSS properties and values:

$.css(property, value)

Set multiple CSS properties and values:

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

Use a function to set CSS properties and values

$.css(selector, function(index, currentValue))

Example

Get the background color of the clicked DIV:

$("div").click(function(){
  $.css("background-color");
});
Test and see‹/›

Set the color property of all paragraphs:

$("button").click(function(){
  $("p").css("color", "blue");
});
Test and see‹/›

Set multiple CSS properties and values:

$("button").click(function(){
  $("p").css({
    "color": "white",
    "font"-size": "1.3em",
    "background"-"color": "#"4285f4",
    "padding": "20px"  
  });
});
Test and see‹/›

Get the width, height, color, and background color of the clicked DIV:

$("div").click(function(){
  let html = ["The clicked div has the following styles:"];
  let styleProps = $(this).css(["width", "height", "color", "background-color]);
  $.each(styleProps, function(prop, value) {
    html.push(prop + ": " + value);
  });
  $("#result").html(html.join("<br>"));}}
});
Test and see‹/›

Use a function to set CSS properties and values:

$("button").click(function(){
  $("p").css("padding", function(i, val){
    return i + 25;
  });
});
Test and see‹/›

Increase the padding of all paragraphs when the button is clicked (using function):

$("button").click(function(){
  $("p").css({
    padding: function(i, val){
      return parseFloat(val) * 1.2;
    }
  });
});
Test and see‹/›

Parameter Value

ParameterDescription
propertySpecify the name of the CSS property
valueSpecify the value of the CSS property
function(index, currentValue)Specify a function that returns the value of the CSS property
  • index-Return the index position of the element in the collection

  • currentValue-Return the current value of the CSS property

jQuery HTML/CSS Methods