Created
January 16, 2022 22:33
-
-
Save souporserious/2402caf0f887450f89d9e240e3a235ff to your computer and use it in GitHub Desktop.
Example of setting up responsive CSS Grid styles with styled-components and TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference types="styled-components/cssprop" /> | |
import * as React from 'react' | |
import { CSSProp } from 'styled-components'; | |
const gridBreakpoints = { | |
small: '@media (min-width: 0px)', | |
medium: '@media (min-width: 720px)', | |
large: '@media (min-width: 1200px)', | |
}; | |
const gridLayouts = { | |
'--grid-margin': `16px`, | |
'--grid-columns': `repeat(6, minmax(0, 1fr))`, | |
[gridBreakpoints.medium]: { | |
'--grid-margin': `minmax(32px, 1fr)`, | |
'--grid-columns': `repeat(12, minmax(0, 1fr))`, | |
}, | |
[gridBreakpoints.large]: { | |
'--grid-columns': `repeat(12, 100px)`, | |
}, | |
gridTemplateColumns: `var(--grid-margin) var(--grid-columns) var(--grid-margin)`, | |
}; | |
type Breakpoints = keyof typeof gridBreakpoints; | |
type VariantStyles = Partial<Record<Breakpoints, CSSProp>>; | |
const variant = ({ small, medium, large, ...styles }: VariantStyles) => { | |
if (small) { | |
styles = { | |
...styles, | |
[gridBreakpoints.small]: small, | |
}; | |
} | |
if (medium) { | |
styles = { | |
...styles, | |
[gridBreakpoints.medium]: medium, | |
}; | |
} | |
if (large) { | |
styles = { | |
...styles, | |
[gridBreakpoints.large]: large, | |
}; | |
} | |
return styles as CSSProp; | |
}; | |
export default function App() { | |
return ( | |
<div css={gridLayouts}> | |
<div css={variant({ small: { gridColumn: '1/-1' }, medium: { gridColumn: '1/6' } })}> | |
Item | |
</div> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment