Skip to content

Instantly share code, notes, and snippets.

@jakedohm
Created May 20, 2020 20:44
Show Gist options
  • Save jakedohm/e4cf43193d89a754935b04dff0960fd0 to your computer and use it in GitHub Desktop.
Save jakedohm/e4cf43193d89a754935b04dff0960fd0 to your computer and use it in GitHub Desktop.
Generate min-width, max-width, and "only" Tailwind screen variants automagically
function generateScreens(screenSizes) {
const getPx = val => `${val}px`
const screenEntries = Object.entries(screenSizes)
const minWidthBreakpoints = screenEntries.reduce(
(acc, [name, width]) => ({
...acc,
[name]: { min: getPx(width) },
}),
{},
)
const maxWidthBreakpoints = screenEntries.reduce(
(acc, [name, width]) => ({
...acc,
[`to-${name}`]: { max: getPx(width) },
}),
{},
)
let prevBreakpointWidth = null
const onlyBreakpoints = screenEntries.reduce((acc, [name, width]) => {
const isFirst = prevBreakpointWidth === null
const key = name + '-only'
const value = isFirst
? { max: getPx(width) }
: { min: getPx(width), max: getPx(prevBreakpointWidth - 1) }
prevBreakpointWidth = width
return { ...acc, [key]: value }
}, {})
return { ...minWidthBreakpoints, ...maxWidthBreakpoints, ...onlyBreakpoints }
}
export { generateScreens }
import { generateScreens } from './generate-tailwind-screens'
module.exports = {
theme: {
screens: {
...generateScreens({ sm: 640, md: 768, lg: 1024, xl: 1280 }),
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment