jQuery CSS Operations - css() Method
Example
Set the color of the <p> element:
$(".btn1").click(function(){ $("p").css("color","red"); });
Definition and Usage
The css() method returns or sets one or more style properties of the matched elements.
Returns CSS property value
Returns the CSS property value of the first matching element.
Note:When used to return a value, shorthand CSS properties are not supported (such as "background" and "border").
$(selector).css(name)
Parameter | Description |
---|---|
name | Required. Specifies the name of the CSS property. This parameter can include any CSS property. For example, "color". |
Example
Get the value of the color style attribute of the first paragraph:
$("p").css("color");
Set CSS property
Sets the specified CSS property for all matching elements.
$(selector).css(name,value)
Parameter | Description |
---|---|
name | Required. Specifies the name of the CSS property. This parameter can include any CSS property, such as "color". |
value |
Optional. Specifies the value of the CSS property. This parameter can include any CSS property value, such as "red". If an empty string value is set, the specified property is removed from the element. |
Example
Set the color of all paragraphs to red:
$("p").css("color","red");
Use a function to set CSS properties
Sets the value of the style property for all matching elements.
This function returns the value to be set for the property. It accepts two parameters, index is the index position of the element in the object collection, and value is the original property value.
$(selector).css(name,function(index,value))
Parameter | Description |
---|---|
name | Required. Specifies the name of the CSS property. This parameter can include any CSS property, such as "color". |
function(index,value) |
Specifies the function that defines the new value of the CSS property.
|
Example 1
Set the color of all paragraphs to red:
$("button").click(function(){ $("p").css("color",function(){return "red";}); });
Example 2
Gradually increase the width of the div:
$("div").click(function() { $(this).css( "width", function(index, value) {return parseFloat(value) * 1.2;} ); });
Set multiple CSS property/value pairs
$(selector).css({property:value, property:value, ...})
Sets the "name/value pair" object as the style property of all matching elements.
This is the best way to set a large number of style properties on all matching elements.
Parameter | Description |
---|---|
{property:value} |
Required. Specifies the "name/value pair" object to be set as the style property. This parameter can include several name/value pairs of CSS properties. For example, {"color":"red","font-weight":"bold"} |
Example
$("p").css({ "color":"white", "background-color":"#98bf21", "font-family":"Arial", "font-size":"20px", "padding":"5px" });