jQuery and CSS: basics

In this post, I'll explain some basic techniques for reading and writing styles by using jQuery.

The css() method

jQuery provides the css() method for reading and writing styles. This method can be attached to every single element on the page. The features of this method are explained below.

Reading styles

The css() method can be used to retrieve a style property of the first matched element. Shorthand properties are not supported. For example, if you want to retrieve the rendered top margin, you should write marginTop instead of margin-top. Example:

$(document).ready(function() {
    var marginTop = $('#test').css('marginTop');
    $('<p></p>').html('The margin-top value of the preceding element is ' + '<strong>' + marginTop + '</strong>.').insertAfter('#test');
});

Writing a single style rule

Another feature of the css() method is the ability of writing a single style rule on the first matched element. In this case, you should put the property name and its value inside quotes and separate them with a comma. For example:


$(document).ready(function() {

  $('#test').css('background', 'lime');

});

Writing multiple style rules

The css() method accepts as its argument a JavaScript object literal where you can write multiple style rules. The syntax is: {'property1': 'value1', 'property2': 'value2', 'propertyn': 'valuen'}. You can also assign your object literal to a variable and then pass it to the css() method. By doing so, your code remains clean and you don't have to write multiple style rules on a single line. Further, your code will be faster because the object literal will be loaded first by the browser. Example:

$(document).ready(function() {

  var cssStyles = {
    'background': 'lime',
    'padding': '0.5em',
    'margin': '1em 0',
    'border': 'thin solid green'
  };
  
  $('#test').css(cssStyles);

});

Leave a Reply

Note: Only a member of this blog may post a comment.