jQuery Tutorial Tutorials - jQuery .css() method

jQuery .css() method

The .css() method in jQuery is used to get/set the value of CSS style property for matched elements.

jQuery .css() method Syntax

.css('propertyName')
.css(arrPropertyNames)
.css('propertyName',value)
.css(propertyName,function)
.css(properties)
Parameter Type Description
propertyName String CSS property
arrPropertyNames Array An array of one or more CSS properties.
value String,Number A value to set for the property.
funtion(index, oldValue) Function a function returning the css style value to set.
index is the position of the element in the set.(based 0)
oldValue is the old value.
properties PlainObject An object of property-value pairs to set.

.css('propertyName')

get one css property for the first matched element.

example

Get the color style of the first li element.

$("li").css("color");

Try now

.css(arrPropertyNames)

get one or more css properties for the first matched element.

example

Get the width and color style of the first li element.

$("li").css( ['width','color'] );

Try now

.css(propertyName,value)

Set value to CSS property propertyName for the set of matched elements.

example

Change the color of any paragraph to red

$("p").css("color","red");

Try now

.css( propertyName, function )

Set a value which function will return to CSS property propertyName for the set of matched elements.

example

Increase the width of #box by 10 pixels each time it is clicked.

$('#box').click(function(){
    $( this ).css( "width", function(index,oldValue){
        return parseInt(oldValue)+ 10;
    });
});

Try now

.css( properties )

Set one or more CSS properties to the set of matched elements.

example

Change the color and background color of paragraph

var styles = {
    backgroundColor : "cyan",
    color: "white"
};
$("p").css( styles );

Try now

jQuery .css() method Notice

$('#box').css('left','100'); // not work 《==
$('#box').css('left','100px'); // It works
$('#box').css('left',100); // It works

$('#box').css('width','100') // It works;
$('#box').css('width','100px') // It works;
$('#box').css('width',100) // It works;

Because there is a hook when set the width,it will adds a "px" unit to the string values.Refer to jQuery.cssHooks for more information.

Date:2019-08-19 16:08:28 From:www.Lautturi.com author:Lautturi