postcss-aspect-ratio-from-bg-image
v0.2.9
Published
PostCSS plugin to generate styles for maintaining block aspect ratio of referenced background image
Downloads
10
Maintainers
Readme
postcss-aspect-ratio-from-bg-image
PostCSS plugin to generate styles for maintaining block aspect ratio of referenced background image (aka Uncle Dave's Ol' Padded Box). JPG, PNG and SVG files are supported.
Demo
Input
.a {
background: url(img.svg)
}
Output
.a {
background: url(img.svg)
}
.a::before {
display: block;
box-sizing: content-box;
padding-bottom: 81%;
content: ''
}
Installation
npm install postcss-aspect-ratio-from-bg-image
Usage
const postcss = require('postcss');
const aspectRatio = require('postcss-aspect-ratio-from-bg-image');
postcss()
.use(aspectRatio())
.process(input, { from: '/path/to/input.css' })
.then(result => {
console.log(result.css);
})
Via postcss.config.js
const aspectRatio = require('postcss-aspect-ratio-from-bg-image');
module.exports = {
plugins: [
aspectRatio()
]
}
Configuration
selector
Type:
string
Default:::before
CSS selector of generated rule. For instance with selector: '.ratio'
output
will looks like:
/* original rule */
.a {
background: url(img.svg)
}
/* generated rule */
.a.ratio {
display: block;
box-sizing: content-box;
padding-bottom: 81%;
content: ''
}
match
Type:
string | RegExp | Array<string | RegExp>
Default:/\.(jpe?g|png|svg)(\?.*)?$/
(any jpg/png/svg file with optional query param, egimg.png?qwe=123
)
Which url()
imports should be processed. Could be a string (glob pattern), RegExp
or array of them. Rules are tested against absolute image path.
// Include all SVGs, except images from node_modules
aspectRatio({
match: [/\.svg$/, '!**/node_modules/**']
});
By default all png, jpg and svg files are affected. If you want to process specific file you can specify query param in import:
.a {background: url(img.svg?ratio)}
and create corresponding rule to match only imports with ?ratio
param:
//
aspectRatio({ match: /\.svg\?ratio$/ });