-
Notifications
You must be signed in to change notification settings - Fork 49
CSS Modules
Kyle Robinson Young edited this page Mar 7, 2016
·
1 revision
- Allow styles to cascade
- Styles authored in a natural way
- Easily composable and extended
- Easily shared on npmjs.com
Inline Styles
Inline styles are easy but they don't allow styles to cascade. They also come with many limitations: no fallbacks, no media queries, no @keyframes, less performance, less security (harder to set a CSP). They should be reserved for non-styling properties, such as settingheight
or positioning.
If we want to create a list element with some default styles applied:
var bel = require('bel')
var csjs = require('csjs')
module.exports = function (data) {
return bel`<ul class="${styles.list}">
${data.map(function (item) {
return bel`<li>${item}</li>`
})}
</ul>`
}
var styles = module.exports.styles = csjs`
.list {
background-color: green;
margin: 0;
padding: 1rem .5rem;
}
.list li {
list-style: none;
}
`
<ul class="${styles.list}">
will set the class to unique class name that represents the .list
CSS declaration.
Now we can extend the styles from the list:
var list = require('./list.js')
module.exports = function () {
var data = [1,2,3]
return bel`<div class="${styles.fancy}">
<h3>Fancy List</h3>
${list(data)}
</div>`
}
var styles = module.exports.styles = csjs`
.fancy ul extends ${list.styles.list} {
background-color: red;
}
`
If you need to quickly inject the styles into your page for development:
npm i csjs-injectify --save-dev
browserify entry.js -o bundle.js -t csjs-injectify
Now the generated styles will be applied in a <style>
tag on your page.
When you're ready to generate and deploy your CSS:
npm i csjs-extractify --save-dev
browserify -p [ csjs-extractify -o dist/bundle.css ] index.js -o dist/bundle.js