Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Created September 6, 2018 18:39
Show Gist options
  • Select an option

  • Save dgowrie/f80a5636e52e38f37ada4dd32361a51c to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/f80a5636e52e38f37ada4dd32361a51c to your computer and use it in GitHub Desktop.
Thin wrapper "macro" for declarative breakpoint media queries in emotion styled components
/**
* Similar to Sass mixins
* Goals are:
* - intuitive, sensible naming convention for ranges
* - declarative syntax
* Two approaches explored...
*/
/* Breakpoints - if we want to keep these as separate variables (pros/cons) */
const phone = '26.563em';
const tablet = '48.000em';
const desktop = '64em';
const breakpoints = {
phone,
tablet,
desktop,
};
/**
* individual 'mixin' per MQ approach
* is arguably easier to reason about and nicer to read
*/
function forTabletUp(styles) {
return `
@media (min-width: ${breakpoints.tablet}) {
${styles}
}
`;
}
function forDesktopUp(styles) {
return `
@media (min-width: ${breakpoints.desktop}) {
${styles}
}
`;
}
/**
* alternative
* pro: a single wrapper
* con: requires mental mapping of these 'range' variables
*/
function forSize(range, styles) {
switch (range) {
case 'tablet-up':
return `
@media (min-width: ${breakpoints.tablet}) {
${styles}
}
`;
case 'desktop-up':
return `
@media (min-width: ${breakpoints.desktop}) {
${styles}
}
`;
default:
return '';
}
}
/* usage of both approaches */
const StyledComponent = styled('div')`
border: 1px solid red;
${forTabletUp(`
background: yellow;
`)}
${forDesktopUp(`
background: green;
`)}
${forSize('desktop-up', `
border-bottom: 3px dotted purple;
`)}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment