Jquery Tutorial : Css Styling

Forums » Bookshelf » Jquery Tutorial » Css Styling

4. CSS Styling and jQuery

  • In this chapter, you are going to learn how to read and/or modify the CSS properties of element(s).

4.1. Reading And Modifying CSS Properties

  • Accessing CSS properties in plain old JavaScript is really a pain because of browser inconsistencies:

    • getComputedStyle() method in standards-based browsers
    • currentStyle and runtimeStyle properties in Internet Explorer
  • As mentioned in the introduction chapter, some CSS properties such as float are named differently in the DOM depending on the browser (styleFloat for IE and cssFloat for W3C standards-compliant browsers).

    [Note]Note

    jQuery handles these browser inconsistencies. For example, it recognizes float, styleFloat, and cssFloat as synonyms for the same property.

4.2. Reading And Modifying CSS Properties

  • jQuery provides the .css() method to allow you to get or set the CSS properties of element(s)

    • You can access CSS properties using their CSS names (e.g., background-color) or DOM name (e.g., backgroundColor).
  • .css(propertyName) returns the value of the CSS property for the first element of the selection:

    $('div').css('backgroundColor');
    [Note]Note

    You cannot retrieve shorthand CSS properties such as margin, border, and background using the .css() method. You must request individual properties, such as margin-left, border-left-width, and background-color.

  • .css('propertyName','propertyValue') sets the CSS property to the given value for all elements in the selection.

    $('.header').css('backgroundColor','yellow');
    • If you need to set more than one property at a time on a selection, you can pass the .css() method an object literal containing CSS properties along with their values:

      $('.article').css({
          'backgroundColor':  '#C2F5BF',
          'borderColor':      'yellow',
          'marginBottom':     '10px'
      });

When you use .css() to change a property, jQuery modifies the element’s style property. For example:

$('#mydiv').css('color', 'green');

is equivalent to:

document.getElementById('mydiv').style.color = 'green';
[Note]Note

You can use shorthand CSS properties (e.g., margin, background, border) only when setting properties. For example, jQuery supports:

$selection.css('border-left', '5px solid #ccc');

For retrieving property values, you must specify individual property names. For example, if you want to retrieve the rendered margin, use: $selection.css('marginTop'), $selection.css('marginRight'), and so on.

4.3. Removing CSS Properties

  • Setting the value of a style property to an empty string removes that property from an element if it has already been directly applied:

    • In the HTML style attribute
    • Through jQuery’s .css() method
    • Through direct DOM manipulation of the style property
  • This technique does not remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

    • jQuery does not provide methods for directly modifying CSS rules.

4.4. CSS Classes

  • We have just discussed how you can use the .css() method to quickly change CSS properties, however this one presents one main drawback:

    • When modifying CSS properties, we modify the style attribute of each element in the selection.
    • This mixes content and presentation, which is poor design.
  • To keep your code clean and maintainable, externalize the presentation in a CSS class that you can then apply to or remove from your selection of elements.
  • jQuery provides you with the ability to apply or remove classes to a selection of elements using three main methods:

    .addClass(className)
    Dynamically adds one or more classes to each of the elements in the selection.
    .removeClass(className)
    Dynamically removes one or more classes to each of the elements in the selection.
    .toggleClass(className)
    Dynamically toggles the presence of one or more classes to each of the elements in the selection.
[Note]Note

For each of these methods, you may provide a space-separated list of class names.

  • You can also use .hasClass(className) to test for the presence of a class on any of the elements in the selection.

4.5. Element Dimensions

  • jQuery provides several methods for querying the size of an element.

    • The value returned is the computed size of the element, not necessarily the size specified in CSS.
    • The value returned is numeric, a unit-less pixel value (e.g., 400, not "400px").
    • When applied to a set of elements, the size of only the first element is returned.

      .height()

      The height of the element itself

      .innerHeight()

      The height including padding

      .outerHeight()

      The height including padding and border, optionally including margin if you also provide a boolean true argument

      .width()

      The width of the element itself

      .innerWidth()

      The width including padding

      .outerWidth()

      The width including padding and border, optionally including margin if you also provide a boolean true argument

  • The height() and width() methods can also act as setters, changing the element size, if you provide a value as an argument.

    • If you provide only a numeric value, jQuery interprets it as pixel units.
    • If you provide a string value, you may use any valid CSS measurement (such as "100px", "50%", or "auto").
    • When applied to a set of elements, it changes the size of all elements in the selection.

In contrast, the .css('height') and .css('width') methods return values with units intact (for example, "400px").

jQuery 1.4.1 and later allows you to provide a function as an argument to .height() and .width(). The function is invoked for each element in the selection, and it receives two arguments: the index position of the element in the set and the current height/width of that element. The function should return the new height/width for that element.

4.6. Element Position

  • The .position() method returns the position object of the first element in the selection relative to its first positioned ancestor (the offset parent).

    • It returns an object containing the properties top and left, with numeric values representing pixel offsets.
    • This method can be used only as a getter.
  • The .offset() method returns the position object of the first element in the selection relative to the document.

    • It returns an object containing the properties top and left, with numeric values representing pixel offsets.
  • You can also use .offset() to change the position of the selection.

    • Provide an object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.
    • If the element’s position style property is currently static, the .offset() method changes it to relative to allow for this repositioning.