Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / CSS

Create CSS class programmatically

5.00/5 (1 vote)
26 Aug 2011CPOL 19.1K  
Create CSS class programmatically

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

ExtJS has a utility function to create CSS class programatically, like the following I once used:

C#
Ext.util.CSS.createStyleSheet('.x-tab-tabmenu-right {' +
            'background: transparent url(/images/tab-menu.gif) no-repeat 0 0;' +
            'border-bottom: 1px solid #8db2e3;' +
            'width:18px;' +
            'position:absolute;' +
            'right:0;' +
            'top:0;' +
            'z-index:1000;' +
            'cursor:pointer;' +
            '} .x-tab-tabmenu-over {background-position: -18px 0;}', 'tabMenu'
        );

When I was writing a Sencha Touch Moble web app, I wanted this functionality, but it does not have it. Then I have to use pure JavaScript as follows (I've made it a function):

C#
addClass: function(css) {
    var styleTag = document.getElementsByTagName('style')[0];
    var originalStyles = '';
    if (! styleTag){
        styleTag = document.createElement('style');
        styleTag.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(styleTag);
    } else {
        originalStyles = styleTag.innerHTML;
    }
    styleTag.innerHTML = originalStyles + css;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)