Styled Components Resources
• 1 min read
Hey! Thanks for stopping by! Just a word of warning, this post
is 6 years old, wow! If there's technical information in here it's more than likely out
of date.
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`;There's a reactions leaderboard you can check out too.
Sign up for the newsletter
Want to keep up to date with what I'm working on?
Join other developers and sign up for the newsletter.
I care about the protection of your data. Read the Privacy Policy for more info.