Giter Club home page Giter Club logo

postcss-srcset's Introduction

PostCSS srcset plugin npm version

Assists in auto-generating background images scaled for different viewport widths.

Install with npm: npm install --save-dev postcss-srcset

What it does

The postcss-srcset plugin provides a CSS function srcset that takes an image path and list of viewport widths. For each width, the plugin will create a media query that applies to that viewport width (and below) and contains a duplicate of the declaration it's used in, with the width appended to the URL in a query string.

The plugin doesn't actually scale the images, but the package includes a webpack loader that you can use to do the job.

Examples

// Code example
const postcss = require('postcss')

postcss([
  require('postcss-srcset')(/* optional options */)
])
/* Input example */
html {
  background: srcset('./myimage.png', 300 500 1000) cover;
  color: white;
}
/* Output example */
html {
  background: url('./myimage.png') cover;
  color: white;
}

@media (max-width: 1000px) {
  html {
    background: url('./myimage.png?size=1000') cover;
  }
}

@media (max-width: 500px) {
  html {
    background: url('./myimage.png?size=500') cover;
  }
}

@media (max-width: 300px) {
  html {
    background: url('./myimage.png?size=300') cover;
  }
}

For a more comprehensive example, see the demo.

Options

You can pass an options object as the first argument to the plugin. Here is an explanation of the available configuration arguments and their default values:

const options = {
  // The name of the function to make available in the css, in case you take
  // offense to my default naming of it.
  function: 'srcset',
  // The function that transforms the image's URL for a given media query.
  // You can return a promise from here if you want to do something async.
  transformUrl: (url, size) => `${url}?size=${size}`
}

postcss([
  require('postcss-srcset')(options)
])

Demo

To run the demo, clone this repo and run npm i && npm start.

Demonstration of the output

Use With Build Tools

This plugin comes with a loader for webpack, but you can use any build tool you like.

Webpack

An example of using the built-in webpack loader:

const srcsetPlugin = require('postcss-srcset')

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [srcsetPlugin()]
            }
          }
        ]
      },
      {
        test: /\.(jpe?g|png)$/,
        resourceQuery: /[?&]size(=|&|\[|$)/,
        use: [
          'url-loader',
          srcsetPlugin.loader
        ]
      }
    ]
  }
}

Other Build Tools

If you want to use another build tool you may have to write it yourself. Unless you're doing something very simple, in which case you can do the image resizing just in the plugin's transformUrl argument.

Either way, if you're happy using the same image resize function that the webpack loader uses, it's available for you to require:

const resizeImage = require('postcss-loader/resize-image');
const fs = require('fs')

var image = fs.readFileSync('myImage.png')
// Arguments: Image buffer, image width
// Returns a promise that resolves to a buffer with the resized image
resizeImage(image, 400).then(
  resized => fs.writeFileSync('myImage-400.png', resized),
  error => console.error('Error in resizeImage:', error)
)

ACK

This file is inspired by (and partly copied from) the srcset-loader; check that out if you want to use srcset in img tags.

postcss-srcset's People

Stargazers

parthbera avatar yuyaohshimo avatar Alyx avatar Alexandre Nicastro avatar Shota Tanno avatar Emanuel Lima avatar Denis Denisov avatar Umar Hansa avatar Manish Bhatia avatar Steven Hargrove avatar Marko Grešak avatar Rafael Santos Sá avatar Oliver Isenrich avatar Landon Cline avatar Tim Searle avatar  avatar Martin Shaw avatar  avatar Abd ar-Rahman Hamidi avatar Michael Danilov avatar Shawn Allen avatar Kevin Peters avatar Paweł Lesiecki avatar Fahd (DAZ) avatar Anton Kulakov avatar Abu Shamsutdinov avatar Marko Bolliger avatar Fernando Prieto Moyano avatar Gaston Glyn Rampersad avatar Anton Petrov avatar Andrey Sitnik avatar Paul Kiddle avatar Dan Train avatar

Watchers

James Cloos avatar Paul Kiddle avatar Peter Dolukhanov avatar Tim Searle avatar Wain Glaister avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.