DEV Community

Cover image for How to use CSS Media Query Breakpoint in Styled-Components
Cagatay Unal
Cagatay Unal

Posted on

How to use CSS Media Query Breakpoint in Styled-Components

Create and Use Breakpoint in Styled-Components

Step 1: Create breakpoints.js and define size, device variables
You can change breakpoints size and add new size.

const size = {
 xs: ‘320px’,
 sm: ‘768px’,
 lg: ‘1200px’,
}
const device = {
 xs: `(min-width: ${size.xs})`,
 sm: `(min-width: ${size.sm})`,
 lg: `(min-width: ${size.lg})`
}
export default {size, device}
Enter fullscreen mode Exit fullscreen mode

Step 2: Use this breakpoints in Styled-Components

import breakpoint from 'Commons/breakpoints';
...
const Component = styled.div`
    @media only screen and ${breakpoint.device.xs}{
        display: none;
    }
    @media only screen and ${breakpoint.device.sm}{
        display: flex;
    }
    @media only screen and ${breakpoint.device.lg}{
        display: flex;
    }
`;
Enter fullscreen mode Exit fullscreen mode

Top comments (12)

Collapse
 
sonangrai profile image
Sonahang Rai

Kada I am a human now 😀

Collapse
 
letam_ profile image
Letam

This is amazing

Collapse
 
jordanfinners profile image
Jordan Finneran

You could also achieve this using CSS Variables which would mean you could ship less Javascript. 🎉
developer.mozilla.org/en-US/docs/W...

Collapse
 
larsejaas profile image
Lars Ejaas

Nobe, unfortunately you cannot use CSS variables to set the breakpoint for the media query. env() variables will fix this, but they aren't ready yet - not sure when they will be? But yeah, you can of course use the css variables inside the styling all you want.

Collapse
 
cagatayunal profile image
Cagatay Unal

Yes, but some browsers do not support the css variable.
caniuse.com/css-variables

Collapse
 
jordanfinners profile image
Jordan Finneran

Only really IE11, which is a security risk for anyone using it. 🙈

Collapse
 
js2me profile image
Sergey S. Volkov

First of all, I liked this post because of image :D

Collapse
 
dilan_ozkaynak profile image
Dilan Ozkaynak

Great stuff!

Collapse
 
alonxx profile image
Alonso Diaz

Ty much!

Collapse
 
buriti97 profile image
buridev

nice

Collapse
 
said_mounaim profile image
Said Mounaim

Good , Thank You

Collapse
 
mailingdelgadomedina profile image
MailingDelgadoMedina

Lovely article super thankful for it