jQuery provides powerful methods to get and set CSS properties on HTML elements without writing verbose JavaScript. The .css() method is the cornerstone of jQuery CSS manipulation, letting you read computed styles or apply new ones dynamically.
Reading CSS Values
Pass a single property name to .css() to retrieve its current computed value. jQuery normalises browser differences so you always get a consistent string back, even for shorthand properties like margin.
Setting CSS Values
Pass two arguments — property and value — to apply a style, or pass a plain object to set multiple properties at once. jQuery automatically appends px to numeric values for length properties, saving repetitive string concatenation.
- Single property:
$('p').css('color', 'red') - Multiple properties:
$('p').css({color: 'red', fontSize: '16px'}) - Reading:
var c = $('p').css('color')
Whenever possible, toggle a CSS class instead of setting inline styles directly. This keeps presentation logic inside your stylesheet and makes code easier to maintain and override.