How should a JavaScript library set default CSS styles (is there a "!notimportant"?)

css, javascript

Solution

When a JS library has a default set of styles that should be used, but should also be overridden, the JS library should include a separate stylesheet.

JavaScript should avoid adding styles directly as much as possible, and defer all styling to CSS where it's reasonable.

It's common for sets of styles to be toggled on and off. The way to elegantly handle these situations are with CSS classes.

A case where it may not be reasonable to simply use external stylesheets is animation. CSS animations could certainly be used, but for cross-browser support, asynchronous interpolation is used to animate styles from one value to another.

Problem

When a JavaScript library creates a `<div>`, it typically sets a class on the div so that the user of the library can style it him/herself. It's also common, however, for the JS library to want to set some default styles for the `<div>`. The most obvious way for the library to do this would be with inline styles: ``` <div style="application's default styles" class="please-style-me"> ... </div> ``` However, this will make the application's default styles trump the user's styles. A workaround is to use nested divs: ``` <div style="application's default styles"> <div class="please-style-me"> ... </div> </div> ``` This works great for many styles like 'font' but fails for others like 'position', where the inner div's style will not override the outer div's. What is the best practice for creating user-stylable elements with defaults in a JavaScript library? I'd prefer not to require users to include a CSS file of defaults (it's nice to keep your library self-contained).

Original source

Related problems