SyntaxStudy
Sign Up
jQuery jQuery Inline Styles
jQuery Beginner 5 min read

jQuery Inline Styles

While CSS classes are preferred for static styles, sometimes you need to apply calculated or dynamic values that cannot be expressed ahead of time in a stylesheet. jQuery's .css() method writes directly to an element's style attribute for exactly these situations.

When to Use Inline Styles

Inline styles are appropriate when the value is computed at runtime — for example, positioning an element based on mouse coordinates, or animating a width to a value fetched from a server. Any style that originates from data rather than design belongs inline.

Removing Inline Styles

Pass an empty string as the value to remove a previously set inline style and fall back to whatever the stylesheet defines: $('el').css('color', ''). This is cleaner than using removeAttr('style'), which wipes all inline styles at once.

  • Set from a variable: $('div').css('left', x + 'px')
  • Remove one rule: $('div').css('opacity', '')
  • Use a function: $('li').css('opacity', function(i){ return 1 - i * 0.1; })

Passing a function to .css() receives the element index and current value, allowing per-element computed styles across an entire matched set.

Example
// Position a tooltip at the cursor
$(document).on('mousemove', function (e) {
    $('#tooltip').css({
        left: e.pageX + 10 + 'px',
        top : e.pageY + 10 + 'px'
    });
});

// Fade items using a function (staggered opacity)
$('ul li').css('opacity', function (index) {
    return 1 - index * 0.15;
});

// Remove a single inline rule
$('#box').css('background-color', '');
Pro Tip

Pass an empty string to .css() to remove an inline rule and fall back to the stylesheet.