@renditions/get-sizes
TypeScript icon, indicating that this package has built-in type declarations

3.1.2 • Public • Published

@renditions/get-sizes

npm version js-standard-style

Generate the sizes attribute for HTML img and picture tags.

Install

npm install @renditions/get-sizes

Usage

import getSizes from '@renditions/get-sizes'

const sizes = getSizes({
  size: '100vw',
  breakpoints: [
    {
      mediaMinWidth: '960px',
      size: '50vw'
    },
    {
      mediaMinWidth: '480px'
    }
  ]
})

console.log({ sizes })
// { sizes: '(min-width: 960px) 50vw,(min-width: 480px) 100vw,100vw' }

Breakpoints

The breapoints argument is expected to be an array sorted by mediaMinWidth in descending order.

To sort the breakpoints automatically, pass true for the second argument:

const sizesConfig = {
  size: '100vw',
  breakpoints: [
    {
      mediaMinWidth: '960px',
      size: '50vw'
    },
    {
      mediaMinWidth: '1440px',
      size: '33vw'
    },
    {
      mediaMinWidth: '480px'
    }
  ]
}

const sizes = getSizes(sizesConfig, true)

console.log({ sizes })
// { sizes: '(min-width: 1440px) 33vw,(min-width: 960px) 50vw,(min-width: 480px) 100vw,100vw' }

The breakpoints array can be also be omitted entirely:

console.log({ sizes: getSizes({ size: '100vw' }) })
// { sizes: '100vw' }

Using with React

import React from 'react'
import getSizes from '@renditions/get-sizes'

const MyImage = ({ size = '100vw', ...rest }) => {
  const sizes = getSizes({ size })

  return <img sizes={sizes} {...rest} />
}

Package Sidebar

Install

npm i @renditions/get-sizes

Weekly Downloads

19

Version

3.1.2

License

Apache-2.0

Unpacked Size

18.2 kB

Total Files

7

Last publish

Collaborators

  • srilq