jQuery CSS method

As working with jQuery in your web pages for different elements, it becomes quite useful if CSS can be applied or changed dynamically for different elements. For example, showing an element by using the jQuery .show method and changing its CSS.

See an example of the $.css method

Similarly, new elements added dynamically by using jQuery and you want to apply CSS by using jQuery as well. An element made hidden by using display: none property of CSS in the stylesheet and you want to make it visible and so on.

jQuery comes up with $.css method that can be used to change/apply CSS to specified element(s) as well as return style properties for the given elements.

Apply single CSS property example

This tutorial explains the “CSS” method of jQuery, let us first look at the syntax of using it.

Syntax of using jQuery’s CSS method

The general syntax of using CSS method is:

selector.css(“css_property”,”property_value”);

You can also apply multiple CSS properties by using the following syntax:

selector.css({“css_property”:”property_value”, “css_property”:”property_value”,……})

Where,

  • the selector can be an element like a paragraph, div etc.
  • .css is jQuery method name to apply/change CSS of the specified element.
  • For the single property, you can simply enclose CSS property in double quotes followed by the property value.

e.g. CSS property name = “color” and value = “red”

  • For setting multiple CSS properties, enclose properties into the curly brackets. Each property is separated by a comma.

e.g. p.css({“color”:”red”, “font-size”:”12px”});

Example of applying single CSS property

The example below applies CSS to a paragraph. This will only set the color of the paragraph text.

Experience this example online

Example of applying multiple CSS properties

The example below applies CSS properties to a paragraph. As you click on the paragraph text, the color, font size, border color, border style of the paragraph are applied CSS properties.

Experience this example online

CSS background image example

The example below sets the background image of the paragraph element by using jQuery css method, as you click on the paragraph text.

Experience this example online

CSS display example

The example below uses CSS jQuery method to display a paragraph element that was hidden by using the display: none; in CSS, as the web page loads.

As you click on the other paragraph text, it will execute jQuery CSS method and apply display: initial; value and paragraph will be displayed.

Experience this example online

Conclusion – CSS in jQuery

As shown in the above examples, you can use the .css method of jQuery to apply CSS to the specified elements. The example of using the border, background, color, font-size are shown. Similarly, you can use other properties like CSS text, margin, padding, hover, visibility etc. by using the $.css method of jQuery.

 

Also see jQuery hover | jQuery $.On | jQuery show