Skip to content

Instantly share code, notes, and snippets.

@JamieBradders
Last active May 25, 2019 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieBradders/913b74b4c97b23372eb5fcd1ac7fe510 to your computer and use it in GitHub Desktop.
Save JamieBradders/913b74b4c97b23372eb5fcd1ac7fe510 to your computer and use it in GitHub Desktop.
A collection of media query helper functions that can be used with Styled Components
/**
* Configure the breakpoint object as you please.
* Edit the values or even add extra keys e.g. `xl`
*/
const breakpoints = {
sm: 768,
md: 1024,
lg: 1200,
}
/**
* The equivalent of
* @media (max-width: 768px) {}
*/
const mediaBelow = lower => {
if (breakpoints[lower]) {
return `(max-width: ${breakpoints[lower]}px)`
} else {
throw new Error(`Your lower breakpoint was invalid ${lower}`)
}
}
/**
* The equivalent of
* @media (min-width: 768px) {}
*/
const mediaAbove = upper => {
if (breakpoints[upper]) {
return `(min-width: ${breakpoints[upper]}px)`
} else {
throw new Error(`Your upper breakpoint was invalid ${upper}`)
}
}
/**
* The equivalent of
* @media (min-width: 768px and max-width: 1024px) {}
*/
const mediaBetween = (lower, upper) => {
if (breakpoints[lower] && breakpoints[upper]) {
return `(min-width: ${breakpoints[lower]}px and (max-width: ${breakpoints[upper] - 1})px)`
} else {
throw new Error(
`Your lower and upper breakpoints were invalid ${lower}, ${upper}`
)
}
}
export { breakpoints, mediaBelow, mediaAbove, mediaBetween }
/**
* Example Page Component
* Here we are using mediaAbove() to adjust the heading's font size
* on devices >= 768px
*/
import React from 'react'
import styled from 'styled-components'
import {mediaAbove} from './helpers'
const Heading = styled.h1`
font-size: 24px;
@media ${mediaAbove('sm')} {
font-size: 48px;
}
`
const Page = () => {
<div>
<Heading>Hello World!</Heading>
</div>
}
export default Page
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment