30 of 119 menu

The css method

The css method allows you to get and change the CSS styles of an element. It is important to remember that we will be getting 'calculated values' properties, which may differ from those specified in the CSS styles.

Syntax

Get one property:

$(selector).css(property);

Get multiple properties, the passed parameter is an array of property names:

$(selector).css(['width', 'height', 'color']);

Change one property:

$(selector).css(property, new value);

Let's change a few properties by passing them as an object containing pairs 'key: value'. The property name is specified in the form CamelCase:

$(selector).css({fontSize: '12px', color: 'red'});

Or, alternatively:

<p class="www">text</p> $('.www').css({'font-size':'12px', 'color':'red'});

We can also apply the given function to each element in the set. In this case, the function will receive the element number in the set as the first parameter, and the current value of the given CSS property for a specific element as the second parameter. In this case, this inside the function will point to the current element. The CSS property of each element will change to the one that the function returns specifically for this element:

$(selector).css(property name, function(number in set, current value of css property));

Example

Let's get all elements with class www and change their color to red:

<p class="www">text</p> $('.www').css('color', 'red');

Example

Let's get all elements with the class www and change their color to red and their font size to 20px:

<p class="www">text</p> $('.www').css({color:'red', fontSize:'20px'});

Or, alternatively:

<p class="www">text</p> $('.www').css({'color':'red', 'font-size':'20px'});

See also

  • method width,
    which allows you to get and change the width of an element
  • method offset,
    which allows you to get the current coordinates of an element
azbydeenesfrkakkptruuz