How to create a CSS rule or class at runtime using jQuery ?

It’s a common practice to write a CSS file for our HTML. Those are called static CSS. When we want to create our Cascading Style Sheet rule at runtime, we need jQuery. The jQuery enables us to apply styles to our HTML dynamically.

The CSS rules once written can be stored in a variable and used multiple times wherever needed.
We use jQuery’s css(“arrtibute1”, “value1”).

Below example illustrates the approach:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>CSS Rules with JQuery</title>
    <script 
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" 
crossorigin="anonymous">
    </script>
</head>
  
<body>
    <div id="myId">
        <h1>GeeksforGeeks</h1>
    </div>
  
    <div class="myclass">
        <h1>A Computer Science Portal for Geeks</h1>
    </div>
  
    <script>
  
        // Here 'my_css' variable stores the Style
        var my_css = {
            backgroundColor: "red",
            color: "rgb(0,255,0)"
        }
        $("#myId").css(my_css);
  
        var my_class_css = {
            background: "green",
            color: "rgb(255,255,255)"
        }
        $(".myclass").css(my_class_css);
    </script>
  
</body>
  
</html>

chevron_right


Output:

Example 2: It also has an alternative where you can directly use a CSS-like styling code instead of a JavaScript-like styling.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>CSS Rules with JQuery</title>
    <script 
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" 
crossorigin="anonymous">
  </script>
</head>
  
<body>
    <div id="myId">
        <h1>Without Coding</h1>
    </div>
  
    <div class="myclass">
        <h1>There are no Geeks</h1>
    </div>
  
    <script>
        $(document).ready(function() {
  
            // Build your CSS.
            var body_css = {
                "background-color": "rgb(0,0,0)",
                "font-weight": "",
                "color": "rgb(255,255,255)"
            }
  
            $("body").css(body_css);
        });
    </script>
  
</body>
  
</html>

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.