jQuery API

.css()

Contents:

.css( propertyName ) Returns: String

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

  • version added: 1.0.css( propertyName )

    propertyNameA CSS property.

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. The .css() method accounts for such differences, producing the same result no matter which term we use. For example, an element that is floated left will return the string left for each of the following three lines:

  1. $('div.left').css('float');
  2. $('div.left').css('cssFloat');
  3. $('div.left').css('styleFloat');

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').

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.

Example:

To access the background color of a clicked div.

<!DOCTYPE html>
<html>
<head>
  <style>
div { width:60px; height:60px; margin:5px; float:left; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

.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 )

    propertyNameA CSS property name.

    valueA value to set for the property.

  • version added: 1.4.css( propertyName, function(index, value) )

    propertyNameA CSS property name.

    function(index, value)A function returning the value to set. Receives the index position of the element in the set and the old value as arguments.

  • version added: 1.0.css( map )

    mapA map of property-value pairs to set.

As with the .attr() 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 map of key-value pairs (JavaScript object notation).

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.

As with .attr(), .css() allows us to pass a function as the property value:

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

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

Examples:

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

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:blue; width:200px; font-size:14px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

Example: To highlight a clicked word in the paragraph.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:blue; font-weight:bold; cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

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

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:green; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

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

<!DOCTYPE html>
<html>
<head>
  <style>
  div { width: 20px; height: 15px; background-color: #f33; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.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>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .css() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • What would be the best possibility to deal with border-spacing? I understand that margin isn't supported (probably because of the same issue). element.css('border-spacing') would return something like "1px 1px" (for horizontal and vertical spacing) and to my knowledge there's no way to ask for each separate?
  • RaniA
    alert($("<div>",{"class":"myclass"}).css("width"));
    Internet Explorer 8 gives me undefined,firefox gives me the right width;
    Also tried it with "stylewidth", but it doesnt work. Anyone got an idea how to fix it so it can also run under IE 8 ?</div>
  • Yo
    Try with:
    alert($("#myclass").css('width'));
  • RaniA
    Still returns undefined, also dont works under firefox
  • Yo
    Sorry, I had a mistake, the correct way is:
    alert($(".myclass").css('width'));
  • Tara_irvine
    is it possible to have $('#divID').css({"left": "+=780px"}); what i'm looking for is $('#divID').animate({"left": "+=780px"}); but I don't want the animation...
    Really stuck :(

  • maybe this works for you?
    $('#divID').css('left', function(index) {
    return index + 780 + 'px';
    });
    taken from the description
  • Actually, that would not do it. The index is not the same thing as the value.

    Try this instead:

    $('#divID').css('left', function(index, val) {
    return (parseFloat(val) + 780) + 'px';
    });
  • You can save the previous "left" value first.

    var oldLeft = parseInt($("#divID").css('left'));
    $("#divID").css('left',oldLeft + 780);

    this works for sure ;)
  • Jake
    Is it possible to get the css of an element's :hover?
  • gsgriffin
    I think what we're looking for in JS and can't find in jQuery is the follow:
    var mysheet=document.styleSheets[0], targetrule; //get the stylesheet..assuming only 1

    var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;//get the all items

    for (i=0; i<myrules.length; all="" for="" i++){="" items="" looking="" loop="" through="" want<br="" what="" you="">
    if(myrules[i].selectorText.toLowerCase()==".daymark:hover"){

    //your search criteria must include the '.' or '#' or whatever it may have before it

    //even if your class has upper case in it, make them lower case in the search

    //my actual class is 'dayMark:hover'

    targetrule=myrules[i]; //assign the rule to targetrule

    break;

    }

    }

    targetrule.style.height=(matrixH-50)+"px"; //make the change the same way you would any other object
    </myrules.length;>
  • Check out the jQuery Rule plugin:
    http://flesler.blogspot.com/2007/11/jqueryrule.html

    In the future, this type of question is better asked on the jQuery forum.
  • anon
    Here is a little function that returns the topmost item from the given jQuery object. It's called maxZ for z-index.
    function maxZ(j)
    {
    var m = 0;
    var mj;
    j.each(function(){
    if ($(this).css("z-index") > m)
    {
    mj = $(this);
    m = $(this).css("z-index");
    }
    });
    return mj;
    }
  • anentropic
    You appear to have to quote the property names if you're using the 'map' form, eg:
    $el.css({'overflow-y': 'hidden'})

    The last example in the docs shows:
    $(this).css({
    width: function(...

    but I get an error if it's not quoted. (FF3.6 OSX)
  • Property names only need quotation marks if those names include characters that aren't permitted (anything other than letter, number, or underscore, if memory serves me correctly) or if they are among JavaScript's list of "reserved" words (such as "class"). So, .css({marginRight: '10px'}) and .css({'margin-right': '10px'}) are fine, but .css({margin-right: '10px'}) is not.
  • covus
    $('el').css('margin-right') returns '0px' if 'margin-right' is set to 'auto'...... this is not correct, it should return 'auto' .
  • Geoffrey
    I agree. This should be uniform across browsers, no?
  • ZQ
    in IE8 return "auto" but in FF return "0px", I think it's because different browsers set different default values of CSS properties.
  • Mark
    I notice that this is case sensitive. .css("Overflow","Auto") doesn't work but .css("overflow","auto") does.
  • Also missing from this new documentation (unless it's changed in the latest version of jQuery) is the fact that if you pass in an empty string for a value to .css(property, value) it will remove the style property from the element. If that functionality has changed, please reply to this to let me know.