SyntaxStudy
Sign Up
jQuery jQuery CSS Manipulation
jQuery Beginner 4 min read

jQuery CSS Manipulation

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.

Example
// Read a CSS value
var bg = $('body').css('background-color');
console.log(bg);

// Set a single property
$('h1').css('color', 'steelblue');

// Set multiple properties at once
$('p').css({
    fontSize  : '18px',
    lineHeight: '1.6',
    color     : '#333'
});

// Numeric value — jQuery adds "px" automatically
$('div.box').css('width', 200);
Pro Tip

Prefer toggling CSS classes over setting inline styles for easier maintenance.