Skip to content
This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
/ get-sizes Public archive

Generate the sizes attribute for HTML img and picture tags.

License

Notifications You must be signed in to change notification settings

renditions/get-sizes

Repository files navigation

@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} />
}