css-inline-stream
v1.0.314
Published
Inline CSS classes into styles from HTML streams
Downloads
689
Maintainers
Readme
CSS Inline Stream
Nothing fancy. Just a chill CSS style inliner that works on streams. Probably the name could be better, as it takes a stream of HTML as input.
This will parse styles out of style tags in the document and for any tags approached after that style, it will attempt to appropriately apply the styles inline on the element in the style attribute.
Order of precedence and all that jazz is handled. CSS vars are removed and inlined too.
It's only been tested for the case of styles being in the head (before any elements that might have classes).
You can see a test of this working on a Bulma CSS site if you run node testinliner
.
It's not perfect, but it's better than the crappy email templates I'd have made painstakingly by hand.
Usage
// testinliner.js
const inliner = require('./css-inliner');
const fs = require('fs');
/**
* e.g.
* ```html
* <html>
*
* <head>
* <style>
* p {
* color: blue;
* }
* </style>
* </head>
*
* <body>
* <p>Hello, world!</p>
* </body>
*
* </html>
* ```
* */
const rs = fs.createReadStream('inline.html');
const is = inliner(rs);
const ws = fs.createWriteStream('output.html');
is.pipe(ws)
.on('finish', () => {
console.log("Finished");
});
/**
* Should output:
* <html>
*
* <head></head>
*
* <body>
* <p style="color: blue">Hello, world!</p>
* </body>
</html>
*
* */
Inspiration
I wanted to be able to send beautifully styled emails from liquidHTML templates generated by Silex CMS (which produce streams of HTML). This works perfectly, except obviously CSS classes aren't supported in most e-mail clients, nor are CSS variables. So, I slapped this together. Happy hacking 💻
Contributing
It's not a lot of code, feel free.
To Do
- [ ] Transform links
- [ ] Accept options (transform links, inline vars)
- [ ] Test cases
- [ ] Types
- [ ] Chill