.css()

jQuery

.css()


Get the value of a style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

Contents:

.css( propertyName )Returns: String

Description: Get the value of style properties for the first element in the set of matched elements.

  • version added: 1.0.css( propertyName )

    • propertyName
      Type: String
      A CSS property.
  • version added: 1.9.css( propertyNames )

    • propertyNames
      Type: Array
      An array of one or more CSS properties.

The .css() method is a convenient way to get a style property from the first matched element, especially in light of the different ways browsers access most of those properties (the getComputedStyle() method in standards-based browsers versus the currentStyle and runtimeStyle properties in Internet Explorer) and the different terms browsers use for certain properties. For example, Internet Explorer's DOM implementation refers to the float property as styleFloat, while W3C standards-compliant browsers refer to it as cssFloat. For consistency, you can simply use "float", and jQuery will translate it to the correct value for each browser.

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor'). Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

As of jQuery 1.9, passing an array of style properties to .css() will result in an object of property-value pairs.

Examples:

Example: Get the background color of a clicked div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span id="result">&nbsp;</span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
<script>
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
</script>
</body>
</html>

Example: Get the width, height, text color, and background color of a clicked div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<head>
<style>
div { height: 50px; margin: 5px; padding: 5px; float: left; }
#box1 { width: 50px; color: yellow; background-color: blue; }
#box2 { width: 80px; color: rgb(255,255,255); background-color: rgb(15,99,30); }
#box3 { width: 40px; color: #fcc; background-color: #123456; }
#box4 { width: 70px; background-color: #f11; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p id="result">&nbsp;</p>
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<script>
$("div").click(function () {
var html = ["The clicked div has the following styles:"];
var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});
</script>
</body>
</html>

.css( propertyName, value )Returns: jQuery

Description: Set one or more CSS properties for the set of matched elements.

  • version added: 1.0.css( propertyName, value )

    • propertyName
      Type: String
      A CSS property name.
    • value
      Type: String or Number
      A value to set for the property.
  • version added: 1.4.css( propertyName, function(index, value) )

    • propertyName
      Type: String
      A CSS property name.
    • function(index, value)
      Type: Function()
      A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
  • version added: 1.0.css( properties )

    • properties
      An object of property-value pairs to set.

As with the .prop() method, the .css() method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single object of key-value pairs.

Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({'background-color': '#ffe', 'border-left': '5px solid #ccc'}) and .css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'}). Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

When using .css() as a setter, jQuery modifies the element's style property. For example, $('#mydiv').css('color', 'green') is equivalent to document.getElementById('mydiv').style.color = 'green'. Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element. Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background> will remove that style entirely from the element, regardless of what is set in a stylesheet or <style> element.

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

As of jQuery 1.4, .css() allows us to pass a function as the property value:

1
2
3
$('div.example').css('width', function(index) {
return index * 50;
});

This example sets the widths of the matched elements to incrementally larger values.

Note: If nothing is returned in the setter function (ie. function(index, style){}), or if undefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Examples:

Example: To change the color of any paragraph to red on mouseover event.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; width:200px; font-size:14px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Just roll the mouse over me.</p>
<p>Or me to see a color change.</p>
<script>
$("p").mouseover(function () {
$(this).css("color","red");
});
</script>
</body>
</html>

Example: Increase the width of #box by 200 pixels

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<style>
#box { background: black; color: snow; width:100px; padding:10px; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="box">Click me to grow</div>
<script>
$("#box").one( "click", function () {
$( this ).css( "width","+=200" );
});
</script>
</body>
</html>

Example: To highlight a clicked word in the paragraph.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<style>
p { color:blue; font-weight:bold; cursor:pointer; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>
Once upon a time there was a man
who lived in a pizza parlor. This
man just loved pizza and ate it all
the time. He went on to be the
happiest man in the world. The end.
</p>
<script>
var words = $("p:first").text().split(" ");
var text = words.join("</span> <span>");
$("p:first").html("<span>" + text + "</span>");
$("span").click(function () {
$(this).css("background-color","yellow");
});
</script>
</body>
</html>

Example: To set the color of all paragraphs to red and background to blue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
<head>
<style>
p { color:green; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Move the mouse over a paragraph.</p>
<p>Like this one or the one above.</p>
<script>
$("p").hover(function () {
$(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
}, function () {
var cssObj = {
'background-color' : '#ddd',
'font-weight' : '',
'color' : 'rgb(0,40,244)'
};
$(this).css(cssObj);
});
</script>
</body>
</html>

Example: Increase the size of a div when you click it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<style>
div { width: 20px; height: 15px; background-color: #f33; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>click</div>
<div>click</div>
<script>
$("div").click(function() {
$(this).css({
width: function(index, value) {
return parseFloat(value) * 1.2;
},
height: function(index, value) {
return parseFloat(value) * 1.2;
}
});
});
</script>
</body>
</html>