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}
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;
}
`;
Top comments (12)
Kada I am a human now 😀
This is amazing
You could also achieve this using CSS Variables which would mean you could ship less Javascript. 🎉
developer.mozilla.org/en-US/docs/W...
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.
Yes, but some browsers do not support the css variable.
caniuse.com/css-variables
Only really IE11, which is a security risk for anyone using it. 🙈
First of all, I liked this post because of image :D
Great stuff!
Ty much!
nice
Good , Thank You
Lovely article super thankful for it