Write SVG lets you write SVGs directly in CSS.
/* before */
@svg square {
@rect {
fill: var(--color, black);
width: 100%;
height: 100%;
}
}
.example {
background: white svg(square param(--color #00b1ff)) cover;
}
/* after */
.example {
background: white url('data:image/svg+xml;charset=utf-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22%3E%3Crect fill=%22%2300b1ff%22 width=%22100%25%22 height=%22100%25%22/%3E%3C/svg%3E') cover;
}
The @svg
at-rule creates a new SVG element available to CSS. This element may be rendered as a data URL by using the svg()
function. Within an @svg
at-rule, descendant at-rules (like @rect
) are transformed into elements, while declarations (like width
) are transformed into attributes. var()
functions may also be used, but their values will be compiled when the SVG element is rendered using the svg()
function.
The svg()
function takes the name of your @svg
at-rule, optionally followed by any number of param()
functions which may be used to pass in variables that may be used with the var()
function.
Add Write SVG to your build tool:
npm install postcss-write-svg --save-dev
require('postcss-write-svg')({ /* options */ }).process(YOUR_CSS);
Add PostCSS to your build tool:
npm install postcss --save-dev
Load Write SVG as a PostCSS plugin:
postcss([
require('postcss-write-svg')({ /* options */ })
]);
Add Gulp PostCSS to your build tool:
npm install gulp-postcss --save-dev
Enable Write SVG within your Gulpfile:
var postcss = require('gulp-postcss');
gulp.task('css', function () {
return gulp.src('./css/src/*.css').pipe(
postcss([
require('postcss-write-svg')({ /* options */ })
])
).pipe(
gulp.dest('./css')
);
});
Add Grunt PostCSS to your build tool:
npm install grunt-postcss --save-dev
Enable Write SVG within your Gruntfile:
grunt.loadNpmTasks('grunt-postcss');
grunt.initConfig({
postcss: {
options: {
processors: [
require('postcss-write-svg')({ /* options */ })
]
},
dist: {
src: 'css/*.css'
}
}
});
Type: String
Default: utf-8
Possible Values: utf-8
, base64
Allows you to define the encoding of an SVG.
/* before { encoding: 'base64' } */
@svg square {
@rect {
fill: var(--color, black);
width: 100%;
height: 100%;
}
}
.example {
background: white svg(square param(--color #00b1ff)) cover;
}
/* after */
.example {
background: white url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IGZpbGw9IiMwMGIxZmYiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiLz48L3N2Zz4=') cover;
}