Define global CSS classes using JavaScript or jQuery?
Asked Answered
V

3

27

Is there a way to set the CSS of global classes using JavaScript or jQuery? That is, append .my_class { foo:bar } to the <style/> tag of the page?

Vidda answered 19/3, 2013 at 7:42 Comment(4)
possible duplicate of Is it possible to alter a CSS stylesheet using JavaScript? (NOT the style of an object, but the stylesheet itself)Lase
Possible duplicate: jQuery create CSS rule / class @ runtimeSopping
Yes but put a large warning in your site's source, alerting anyone who works on the site in the future. In my experinece, sites with dynamically built/amended stylesheets are the most confusing things in the known universe.Bolero
Sorry, I knew this would most likely be a duplicate question but I've spent a few minutes searching it yesterday and could only find irrelevant links - mostly because the results were overshadowed by info about jQuery's .addClass.Vidda
E
44

Pure javascript -

var style=document.createElement('style');
style.type='text/css';
if(style.styleSheet){
    style.styleSheet.cssText='your css styles';
}else{
    style.appendChild(document.createTextNode('your css styles'));
}
document.getElementsByTagName('head')[0].appendChild(style);
Eichelberger answered 19/3, 2013 at 7:59 Comment(5)
Well there are two right answers... chosing by Math.random().Vidda
While both answers provide a correct solution for the given question, I prefer to use pure javascript for performance reasons whenever I'm not trying to support old IE versions.Methylene
I'm adding the global CSS as soon as possible so that new elements are rendered respecting that new CSS. At this time, jQuery is not loaded yet and therefore pure JS is better optionDoublecross
Why there's that IF?Doublecross
IF for browsers testing for the support of dynamic stylesheet, old IE in particular...Eichelberger
M
27

Yes, you can do that in jQuery:

var styleTag = $('<style>.my_class { foo: bar; }</style>')
$('html > head').append(styleTag);

It works by simply appending <style> tag at the end of <head>.

Marney answered 19/3, 2013 at 7:46 Comment(2)
Well there are two right answers... chosing by Math.random().Vidda
multiline styles: let styles = `your styles here multiline`; and then: var styletag = $(styles);Doll
F
5

This seems to be the way in 2023:

const sheet = new CSSStyleSheet()
sheet.replaceSync('div {padding: 2px;}')
document.adoptedStyleSheets = [sheet]

Add more styles to existing sheet:

let index = sheet.cssRules.length
sheet.insertRule('span {color: red;}', index)
Fieldpiece answered 20/8, 2023 at 9:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.