Skip Navigation

Scott Spence

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:

const sizes = {
  monitor: 1800,
  giant: 1500,
  desktop: 992,
  tablet: 768,
  phone: 376,
}

// iterate through the sizes and create a media template
export const media = Object.keys(sizes).reduce(
  (accumulator, label) => {
    // use em in breakpoints to work properly cross-browser and support users
    // changing their browsers font-size: https://zellwk.com/blog/media-query-units/
    const emSize = sizes[label] / 16
    accumulator[label] = (...args) => css`
      @media (max-width: ${emSize}em) {
        ${css(...args)};
      }
    `
    return accumulator
  },
  {}
)

Then to use it in the project:

const PageContainer = styled.div`
  ${media.monitor`
    background: goldenrod;
  `};
  ${media.giant`
    background: goldenrod;
  `};
  ${media.desktop`
    background: dodgerblue;
  `};
  ${media.tablet`
    background: mediumseagreen;
  `};
  ${media.phone`
    background: palevioletred;
  `};
`

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.

Copyright © 2017 - 2026 - All rights reserved Scott Spence