styled-mediate
v0.0.20
Published
A different media query syntax for styled-components
Downloads
9
Maintainers
Readme
Styled Mediate 👩⚖️
A different media query syntax for styled-components
💅. It can be difficult to keep track of where a property gets overwritten on a component with multiple media queries, especially as your component styles get bulky. Instead of writing and re-writing the same property name inside several media queries, What if you could write it once and define all of it's different properties together?
examples
import mediate from 'styled-mediate'
const media = mediate(size => (
`screen and (min-width: ${size}em)`
))
const ExampleNew = styled.div`
display: flex;
${media`
flex-direction: ${{ 0: 'column', md: 'row' }};
background: ${{ 0: 'tomato', sm: 'lime', lg: 'plum' }};
height: ${
({ flag }) => ({ 0: '100px', lg: flag ? '200px' : '150px' })
};
`}
`
const ExampleOld = styled.div`
width: 100px;
height: 100px;
flex-direction: column;
${media.sm`
background: lime;
`}
${media.md`
flex-direction: row;
`}
${media.lg`
background: plum;
height: ${({ flag }) => flag ? '200px' : '150px'}
`}
`
...
<ThemeProvider
theme={{ breakpoints: { sm: 30, md: 45, lg: 60 } }}
>
<ExampleNew flag>
...
</ExampleNew>
</ThemeProvider>
import mediate from 'styled-mediate'
const media = mediate(size => `screen and (min-width: ${size}em)`)
const Example = styled.div`
display: Flex;
${media`
flex-direction: ${{ 0: 'column', md: 'row' }};
& > p {
margin: ${() => (flag ? { 0: '1rem', md: '2rem' } : '3rem')};
}
`}
`
...
<ThemeProvider theme={{ breakpoints: { sm: 30, md: 45, lg: 60 } }}>
<Example flag>
<p>Oh hey! hi, how's it going?<p>
</Example>
</ThemeProvider>
The resulting stylesheet will have it's media queries grouped by component (as usual) and will not include any empty media queries. Also, media queries will appear in their proper order for use with either min or max properties. All automatically.
mediate
takes a single parameter which is a function that is used to generate media queries. This passed-in function's only parameter is the value from the theme provided (theme.breakpoints
) that will be used for the media query associated with that value. The string this function returns is used to create a series of media queries that will wrap the CSS provided to the function by mediate
. This returned function takes CSS and returns a series of media queries (any value that evaluates to 0
will not be wrapped in a media query). mediate
loops over the keys used inside the CSS template string object values and generates media queries with the matching breakpoints from the theme provided (theme.breakpoints
).