Open In App

How to Define Multiple CSS Attributes in jQuery ?

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In jQuery, you can define multiple CSS attributes for an element using the css() method. This method allows you to set one or more CSS  properties for an element. In this article, we will see the different ways to define multiple CSS attributes in jQuery.

Syntax: The syntax for defining multiple CSS attributes using the jQuery css() method.

$(selector).css({
     propertyName1 : value1,
     propertyName2 : value2,
     ...
     propertyNameN : valueN,
});

Where,

  •  ‘$(selector)’ is the element(s) you want to apply the CSS to.
  • The ‘propertyName1 : value1‘, ‘propertyName1 : value2‘, etc. are the CSS attributes and their corresponding values you want to set for the element(s).

 Approaches: There are two approaches to defining multiple CSS attributes in jQuery.

  • Using an object literal: You can pass an object literal containing the CSS attributes and their value to the css() method.
  • Using individual arguments: You can pass each CSS attribute and its value as separate arguments to the css() method.

Example 1: In this example, we are using an object literal to define multiple CSS attributes, i.e., we are using an object literal to define the ‘color’, ‘background-color’, and ‘font-size’ CSS attributes for the element with the ID ‘myElement’.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body style='text-align:center'>
    <h1 style='color:green'>
        Geeksforgeeks
    </h1>
  
    <h2 id='myElement'>
        Define multiple CSS attributes
    </h2>
  
    <script>
        $('#myElement').css({
            'color' : 'red',
            'background-color' : 'yellow',
            'font-size' : '24px'
        });
    </script>
</body>
  
</html>


Output:

 

Example 2: in this example, we are using individual arguments to define multiple CSS attributes, i.e., we are using individual arguments to define the ‘color ‘, ‘background-color’, and ‘ font-size’ CSS attributes for the element with the ID ‘myElement ‘. We are chaining the css() method to apply each attribute separately.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body style='text-align:center'>
    <h1 style='color:green'>
        Geeksforgeeks
    </h1>
  
    <h2 id='myElement'>
        Define multiple CSS attributes
    </h2>
  
    <script>
        $('#myElement').css('color' , 'red')
        .css('background-color' , 'yellow')
        .css('font-size' , '24px');
    </script>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads