Using @screen breakpoints #186
-
Hey! Thanks for your work on this library it's really amazing! I'm refactoring some components and they originally used the @screen directive to apply custom styles, is there a way to easily do this with twin.macro? Or do i need to generate some media queries from the breakpoints I have defined? Best, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I've been meaning to publish a half-decent answer on this so thanks for asking the question. Here are some Twin alternatives to the Use @screen in a pluginThis gives you direct access to the screen values from your config. // tailwind.config.js
module.exports = {
// ...
plugins: [
paddings
],
}
function paddings({ addComponents, theme }) {
addComponents({
'.custom-paddings': {
'@screen md': {
'padding-left': theme`padding.3`,
'padding-right': theme`padding.3`,
},
'@screen lg': {
'padding-left': theme`padding.6`,
'padding-right': theme`padding.6`,
},
},
})
} // Usage
<App tw="custom-paddings" />
// or
const Component = tw.div`custom-paddings` Create a custom breakpoint style using the theme importYou could import a single breakpoint and create custom rules with it, then just slot it into a styled/css prop. // Something.js
import React from 'react'
import tw, { css } from 'twin.macro'
const myStyles = css`
@media (min-width: ${theme`screens.md`}) {
h1 {
${tw`text-2xl`};
}
}
`
// Usage
const Component = () => <div css={[myStyles, tw`block`]} />
// or
const Component = styled.div([myStyles, tw`block`]) Create a custom breakpoint helper using the theme importThe theme import got upgraded recently to allow you to grab objects from your merged tailwind.config.js file. This means that once you've got the import { theme } from 'twin.macro'
const breakpoints = theme`screens`
// ↓ ↓ ↓ ↓ ↓ ↓
const breakpoints = {
"sm": "640px",
"md": "768px",
"lg": "1024px",
"xl": "1280px",
}; |
Beta Was this translation helpful? Give feedback.
-
Awesome, that's what i figured. Just incase anyone is wondering I have gone for the last option, and I generate the queries with a function like this: const breakpoints = {
sm: 800,
md: 1040,
lg: 1296,
xl: 1552,
};
const mediaQueries = Object.keys(breakpoints).reduce((obj, key) => ({ ...obj, [key]: `@media (min-width: ${breakpoints[key]}px)` }), {})
// Then you can do things like...
const Button = styled.button`
${tw`text-blue`}
${mediaQueries.md} {
width: 666px;
}
` |
Beta Was this translation helpful? Give feedback.
I've been meaning to publish a half-decent answer on this so thanks for asking the question.
Here are some Twin alternatives to the
@screen
directive for vanilla Tailwind:Use @screen in a plugin
This gives you direct access to the screen values from your config.
A potential downside is that you need to write the plugin using vanilla css: