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.