Skip to content

Instantly share code, notes, and snippets.

@wKovacs64
Created May 26, 2020 14:25
Show Gist options
  • Save wKovacs64/1f9fcd69a5ce7ca3f7a3189319b2390e to your computer and use it in GitHub Desktop.
Save wKovacs64/1f9fcd69a5ce7ca3f7a3189319b2390e to your computer and use it in GitHub Desktop.
CSS-in-JS Media Query Utility Function in TypeScript
const breakpointMap = {
// mobile-first, so there is no 'xs' for portrait phones
sm: 576, // landscape phones
md: 768, // tablets
lg: 992, // landscape tablets and desktops
xl: 1200, // extra large desktops
};
type Breakpoints = typeof breakpointMap;
type BreakpointLabel = keyof Breakpoints;
type MediaQueries = { [BL in BreakpointLabel]: string };
export const mq: MediaQueries = (Object.entries(breakpointMap) as Array<
[BreakpointLabel, Breakpoints[BreakpointLabel]]
>).reduce<Partial<MediaQueries>>((accumulator, [label, bp]) => {
accumulator[label] = `@media (min-width: ${bp}px)`;
return accumulator;
}, {}) as MediaQueries;
// Usage example:
//
// css`
// color: 'white';
// ${mq.md} {
// color: 'papaya';
// }
// `
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment