ScottSpence.com

Scott's Digital Garden.

🤫This is a private post👀

Styled Components Resources

A curated list of hints and tips for using styled-components.

Breakpoints

The first way I found how to do @media queries in styled-components was documented on a Gist.

This is a lift and drop from an old project:

1const sizes = {
2 monitor: 1800,
3 giant: 1500,
4 desktop: 992,
5 tablet: 768,
6 phone: 376,
7}
8
9// iterate through the sizes and create a media template
10export const media = Object.keys(sizes).reduce(
11 (accumulator, label) => {
12 // use em in breakpoints to work properly cross-browser and support users
13 // changing their browsers font-size: https://zellwk.com/blog/media-query-units/
14 const emSize = sizes[label] / 16
15 accumulator[label] = (...args) => css`
16 @media (max-width: ${emSize}em) {
17 ${css(...args)};
18 }
19 `
20 return accumulator
21 },
22 {}
23)

Then to use it in the project:

1const PageContainer = styled.div`
2 ${media.monitor`
3 background: goldenrod;
4 `};
5 ${media.giant`
6 background: goldenrod;
7 `};
8 ${media.desktop`
9 background: dodgerblue;
10 `};
11 ${media.tablet`
12 background: mediumseagreen;
13 `};
14 ${media.phone`
15 background: palevioletred;
16 `};
17`

Back to Top