Menu
- Why Eleventy?
- Get Started
- Community
- Working with Templates
- Using Data
- Configuration
- Template Languages
- Plugins
- API Services
- Release History
- Advanced
5.81s
12.52s
Quick Tip #001—Inline Minified CSS
Originally posted on The Simplest Web Site That Could Possibly Work Well on zachleat.com
This tip works well on small sites that don’t have a lot of CSS. Inlining your CSS removes an external request from your critical path and speeds up page rendering times! If your CSS file is small enough, this is a simplification/end-around for Critical CSS approaches.
Installation Jump to heading
npm install clean-css
to make the CSS minifier available in your project.
Configuration Jump to heading
Add the following cssmin
filter to your Eleventy Config file:
const CleanCSS = require("clean-css");
module.exports = function(eleventyConfig) {
eleventyConfig.addFilter("cssmin", function(code) {
return new CleanCSS({}).minify(code).styles;
});
};
Create your CSS File Jump to heading
Add a sample CSS file to your _includes
directory. Let’s call it sample.css
.
body {
font-family: fantasy;
}
Capture and Minify Jump to heading
Capture the CSS into a variable and run it through the filter (this sample is using Nunjucks syntax)
<!-- capture the CSS content as a Nunjucks variable -->
{% set css %}
{% include "sample.css" %}
{% endset %}
<!-- feed it through our cssmin filter to minify -->
<style>
{{ css | cssmin | safe }}
</style>
Using JavaScript templates Jump to heading
Contributed by Zach Green
You can also inline minified CSS in a JavaScript template. This technique does not use filters, and instead uses async
functions:
const fs = require("fs/promises");
const path = require("path");
const CleanCSS = require("clean-css");
module.exports = async () => `
<style>
${await fs
.readFile(path.resolve(__dirname, "./sample.css"))
.then((data) => new CleanCSS().minify(data).styles)}
</style>`;
Warning about Content Security Policy Jump to heading
style-src
directive allows 'unsafe-inline'
. Otherwise, your inline CSS will not load.
All Quick Tips
#001
—Inline Minified CSS#002
—Inline Minified JavaScript#003
—Add Edit on GitHub Links to All Pages#004
—Zero Maintenance Tag Pages for your Blog#005
—Super Simple CSS Concatenation#006
—Adding a 404 Not Found Page to your Static Site#007
—Fetch GitHub Stargazers Count (and More) at Build Time#008
—Trigger a Netlify Build Every Day with IFTTT#009
—Cache Data Requests#010
—Transform Global Data using an `eleventyComputed.js` Global Data File#011
—Draft Posts using Computed Data- View all of the Eleventy Quick Tips.