logo
post image

How to Add CSS Rules to a Stylesheet with Javascript

Use-Cases of this Tutorial

  • You are looking to add, delete or update CSS rules in an existing / new stylesheet with Javascript.
  • You are looking to create dynamic keyframes CSS rules.

Just Hard-coding the CSS in Stylesheet Will Do. Then Why Dynamically Add the CSS Rules to a Stylesheet with Javascript ?

You must be wondering what would be the real need to add CSS rules to a stylesheet with Javascript. A better way would be to just hard-code the CSS properties in the stylesheet? Or changing the CSS properties of the element with Javascript will also work?

Sometimes the requirement is such that there is no option, other than using Javascript to add CSS to a stylesheet.

One such case is the CSS keyframes rule. Consider the below CSS rule :

@keyframes outlightbox
{ 
	0% { 
		height: 100%;
		top: 0px;
	} 
	100% {
		height: 500px;
		top: 50px;
	}
}   

You can obviously hard-code this CSS rule in a stylesheet. But what when you don't know the value of top in advance? The value of top may be dependent on the initial position of the element, or can be only set after a particular event occurs, or some other complex case.

Adding the keyframes rule to an element with Javascript or jQuery is not possible.

// There is no such thing as this 
$("#element").css('keyframes', ....);

In this case you have no option but to dynamically add the keyframes rule to a stylesheet using Javascript.

Animating a Lightbox with CSS & Javascript is a perfect example where you need to add CSS to a stylesheet dynamically.

Creating a New Stylesheet To Add CSS Rules

When dynamically creating CSS rules it is alays better to create a new stylesheet, and adding rules to it. It is because adding new CSS rules requires the index position where the new CSS rule is to be added. This is relatively simpler in a new stylesheet as the starting index is 0.

Creating and get reference to the new stylesheet with Javascript :

var element = document.createElement('style'),
	sheet;

// Append style element to head
document.head.appendChild(element);

// Reference to the stylesheet
sheet = element.sheet;

Creating and get reference to the new stylesheet with jQuery :

$("head").append('<style id="new-animations" type="text/css"></style>');

var sheet = $("#new-animations").get(0).sheet;

Using an Existing Stylesheet To Add CSS Rules

Although not recommended, but for the sake of showing it, here is how you can get reference to an existing stylesheet.

Assuming the stylesheet is of the form :

<style type="text/css" id="new-animations">
......
......
</style>

With Javascript :

var sheet = document.getElementById('new-animations').sheet

With jQuery :

var sheet = $("#new-animations").get(0).sheet

Adding a New CSS Rule in an Empty Stylesheet

You can insert a new CSS rule using the insertRule method.

var styles = '.new-animation {';
styles += 'text-align:right;';
styles += 'line-height:150px !important;'
styles += '}';

// Add the first CSS rule to the stylesheet
sheet.insertRule(styles, 0);

The second parameter is the position or index of the CSS rule in the stylesheet. Index starts from 0. You cannot give an arbitrary position - the index of the new CSS rule must be after the index of the last CSS rule in the stylesheet.

The below code will give an error because after the 0th index is inserted, the code tries to insert new rule at the 2nd index.

// In an empty stylesheet, this is incorrect
var styles1 = '.new-animation-1 {';
styles1 += 'line-height:150px;'
styles1 += '}';
sheet.insertRule(styles1, 0);

var styles2 = '.new-animation-2 {';
styles2 += 'line-height:100px;'
styles2 += '}';
sheet.insertRule(styles2, 2);

After the 0th position, the next position to be filled should be 1.

Another thing to note is that the newly injected CSS rules will probably not be seen when you use browser developer tools (Inspect Element). Nevertheless the CSS rules are being updated in the DOM.

Adding a New CSS Rule in an Existing Stylesheet

In an already existing stylesheet, CSS rules must be already present. So in order to append a new CSS rule, you must first find the length of CSS rules in the stylesheet, then use that to insert a new rule.

// The no of available CSS rules in the sheet
// This will be the index of the next to-be-added rule
var css_rules_num = sheet.cssRules.length;

sheet.insertRule("#container { margin:5px; }", css_rules_num);

Deleting an Existing CSS Rule

You can delete an existing CSS rule using the deleteRule method.

// This will delete the first rule from the stylesheet
sheet.deleteRule(0);

Note that after deletion, the indexes of the rest of the CSS properties in the stylesheet will rearrange, just like deleting an element from an array will rearrange the array.

Updating an Existing CSS Rule

Very interestingly, updating a CSS rule at a paticular index is not possible. If you try to re-insert a new CSS rule at an occupied position, both the CSS rules will be updated in the DOM ! So take care.

So in order to update a CSS rule at a particular index, first delete the old rule and then insert the new rule.