Dive Into Greasemonkey

Teaching an old web new tricks

4.13. Adding CSS styles

I have often found the need to add my own CSS styles to a page. You can add styles that override existing styles, or styles specific to new elements that your user script inserts.

Example: Make paragraph text larger

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle('p { font-size: large ! important; }');

This function takes one argument, a string containing the style rules you want to add to the page. It works by quite literally injecting a <style> element into the page's <head> section that contains your style rules. Firefox automatically picks up the change, parses the style rules, and applies them to the page. You may include as many separate style rules as you like in a single function call; just concatenate them together as a string and pass them all at once.

[Tip]

You can use the addGlobalStyle function to style elements that you insert into a page, or elements that were part of the original page. However, if you are styling existing elements, you should use the ! important keyword for each rule you define to ensure your styles override the rules defined by the original page.

← Adding images without hitting a central server
Getting an element's style →