Last active
May 25, 2019 11:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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