- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Add CSS Rules to a Stylesheet with JavaScript?
The insertRule() helps us add a rule at a defined position in the stylesheet while deleteRule() deletes a specific style .
The following examples illustrate CSS rules that can be added to a stylesheet using JavaScript.
Example
<!DOCTYPE html> <html> <head> <style type="text/css" id="custom"> body { background-color: silver; } </style> </head> <body> <h1>Custom CSS!</h1> <p>Woohoo!</p> <script> let newSheet = document.getElementById('custom').sheet let cs = 'p {'; cs += 'margin: 4%;'; cs += 'padding: 2%;'; cs += 'font-size: 22px;'; cs += 'box-shadow: -10px 4px 0 chartreuse;' cs += '}'; newSheet.insertRule(cs, 0); </script> </body> </html>
Output
This will produce the following result −
Example
<!DOCTYPE html> <html> <head> <style type="text/css" id="demo"> div { margin: 3%; text-align: center; background-color: powderblue; } p { box-shadow: 0 0 12px rgba(0,0,0,0.6); } h2 { color: red; } </style> </head> <body> <div> <h2>Custom CSS!</h2> <p>Woohoo!</p> </div> <script> let mySheet = document.getElementById('demo').sheet let cs = 'h2 { border: 2px solid green; }' mySheet.deleteRule(2); mySheet.insertRule(cs, 0); </script> </body> </html>
Output
This will produce the following result −
- Related Articles
- How to add CSS rules into an HTML document
- How to add rounded corners to a button with CSS?
- How to add a border to an image with CSS?
- How to add a button to an image with CSS?
- How to add a colored border to a button with CSS?
- How to add a form to a full-width image with CSS?
- With CSS add transparency to a button
- How to add visual effects to images with CSS?
- How to add transition on hover with CSS?
- Add a color to the shadow with CSS
- How to add link dividers in a Navigation Bar with CSS
- How to add a navigation menu on an image with CSS?
- How to flip an image (add a mirror effect) with CSS?
- Add shadow to elements with CSS
- How to add hours and minutes to a date with JavaScript?

Advertisements