Apply Multiple CSS Properties Using jQuery



Apply multiple CSS properties using jQuery CSS( {key1:val1, key2:val2....}) method. We can apply as many properties as we like in a single call.

Syntax

In the below mentioned way we can use the CSS. Here you can pass key as property and val as its value of that property.

selector.css( {key1:val1, key2:val2....keyN:valN})

Define Multiple CSS Attributes in jQuery

As we mentioned earlier that we will be using jQuery css() method to apply multpile CSS properties on any element.

  • First we will use '$(selector)' to select the element where we wants to apply our CSS properties.
  • Then we will add CSS properties one by one in the 'key: value'; format. We can use CSS porperties as an object literal or as an indivitual argument, as we want.

Ways to Define CSS Property in jQuery

There are two ways to include CSS through jQuery.

  • Object Literal: In this way we can pass multiple CSS properties ad values as an object literal.
$('#tutorialsPoint').css({ 
            'color' : 'green', 
            'background-color' : 'gray', 
            'font-size' : '16px' 
}); 
  • Individual Arguments: Here we can keep the property and value pair as a separate argument.
  • $('#tutorialsPoint')
      .css('color', 'green')
      .css('background-color', 'gray')
      .css('font-size', '16px');
    

    Both of the ways are useful, personally we recommend you to use the Object Literal way.

    Example

    In this following example we have applied multiple CSS on two elements in different ways as we described above.

    <!DOCTYPE html>
    <html>
    
    <head>
        <title>Define Multiple CSS Attributes in jQuery</title>
        <!-- jQuery CDN Link -->
        <script src=
    "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
        </script>
    </head>
    
    <body>
        <div>
            <div id="child1">
                Define Multiple CSS Attributes in jQuery
            </div>
            <div id="child2">
                <p>
                    As we have used both the ways to apply
                    CSS through jQuery. Multiple CSS are define
                    in a single call.
                </p>
            </div>
        </div>
        <script>
            // Object Literal Way
            $('#child1').css({
                'margin' : '5px',
                'font-size': '24px',
                'font-weight': 'bold'
            });
    
            // Individual Arguments Way
            $('#child2')
                .css('padding', '10px')
                .css('background-color', 'lightgray')
                .css('font-size', '16px');
        </script>
    </body>
    
    </html>
    
    Updated on: 2024-07-01T15:58:25+05:30

    16K+ Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements