Kai Faust

Build your Own Media Query Framework

Here's a simple framework for your styled-components-powered app! Feel free to copy this code into your project.

import { css } from "styled-components"

/* Customize this to your needs. */
const breakpoints = {
  lv4: 1248,
  lv3: 1152,
  lv2: 768,
  lv1: 480,
  lv0: 0,
}

/* Input a breakpoint ID and get a CSS @media output. */
export const viewportWidth = Object.keys(breakpoints).reduce((mixin, breakpointName) => {
  mixin[breakpointName] = (...args) => css`
    @media (min-width: ${breakpoints[breakpointName]}) {
      ${css(...args)}
    }
  `
  return mixin
}, {})

export const viewportHeight = Object.keys(breakpoints).reduce((mixin, breakpointName) => {
  mixin[breakpointName] = (...args) => css`
    @media (min-height: ${breakpoints[breakpointName]}) {
      ${css(...args)}
    }
  `
  return mixin
}, {})

How to Use It

const Button = styled.a`
  /* Expands button width when viewport width > 768px */
  ${viewportWidth.lv2`
    width: 100%;
  `}

  /* Expands button height when viewport height > 1248px */
  ${viewportHeight.lv4`
    height: 48px;
  `}
`

This will handle most cases. It's what this site is built on!

If you liked this, you might also want to check out my SCSS framework.


Kai Faust
CEO at Foundation Labs

READ THIS NEXT

Goodbye Classes, Hello Props

Advancements in front-end web development have sparked an enormous community effort to improve the way we style applications. We saw an explosion of new styling technologies in 2015 after Facebook...