Dynamic media queries function to use with styled components

––– views

1 min read

Writing media queries is something we all must do, after all, today more than 80% (totally made up statistic) of your visitors are going to come from a mobile device.

When writing these you may have used the CSS variables approach which is fine, but with styled components, you can do something even better. ⁠ ⁠Here is an example of how my approach looks like

CSS

@media ${device.tablet} {
width: 100%;
}

As simple as that, and because this is javascript when you start typing ${device.'it autocompletes this part'}

Below you find the function that is used to achieve this. I've commented on the standard sizes you will likely need to use. However, I also left the sizes I've added throughout my project development. And I think this is the best approach when it comes to responsive design, not just following standards but adding your own, every website is different and needs unique tweaking.

Function

JS

const size = {
mobileS: "320px",
mobileMS: "345px",
mobileM: "375px",
mobileL: "425px",
mobileXL: "520px",
tabletMini: "620px",
tablet: "768px", // Standard
laptopS: "930px",
laptop: "1024px", // Standard
laptopL: "1360px",
laptopM: "1440px", // Standard
desktop: "2560px",// Standard
};
export const device = {
mobileS: `(max-width: ${size.mobileS})`,
mobileM: `(max-width: ${size.mobileM})`,
mobileMS: `(max-width: ${size.mobileMS})`,
mobileL: `(max-width: ${size.mobileL})`,
mobileXL: `(max-width: ${size.mobileXL})`,
tabletMini: `(max-width: ${size.tabletMini})`,
tablet: `(max-width: ${size.tablet})`,
laptopS: `(max-width: ${size.laptopS})`,
laptop: `(max-width: ${size.laptop})`,
laptopM: `(max-width: ${size.laptopM})`,
laptopL: `(max-width: ${size.laptopL})`,
desktop: `(max-width: ${size.desktop})`,
desktopL: `(max-width: ${size.desktop})`,
};
To comment please authenticate