Tailwind CSS - Responsive breakpoints as components

22,133

Solution 1

I found the @screen directive, that solves this question:

https://tailwindcss.com/docs/functions-and-directives/#screen

as easy as

@screen md {
  // whatever
}

Solution 2

By tailwind You can use and Customizing the default breakpoints for your project.

  1. Open your tailwind.config.js

  2. Update/add screens inside your module.exports:

    theme: {
      screens: {
        'sm': '640px',
        // => @media (min-width: 640px) { ... } 
    
        'md': '768px',
        // => @media (min-width: 768px) { ... }
    
        'lg': '1024px',
        // => @media (min-width: 1024px) { ... }
    
        'xl': '1280px',
        // => @media (min-width: 1280px) { ... }
      }
    }
    

Source: https://tailwindcss.com/docs/breakpoints

Solution 3

in tailwind.config.js

const defaultTheme = require("tailwindcss/defaultTheme");

module.exports = {
  
  theme: {
    screens: {
      // adding xs to the rest
      xs: "475px",
      // if you did not add this, you would have only "xs"
      ...defaultTheme.screens,
    },
  },
  
};
Share:
22,133
aitor
Author by

aitor

Updated on July 09, 2022

Comments

  • aitor
    aitor almost 2 years

    How should I deal with responsive breakpoints as components in Tailwind?

    Without Tailwind, I used to declare breakpoints as a scss mixins:

    @mixin tablet-portrait {
      @media (min-width: 700px) {
        @content;
      }
    }
    

    Then:

    @include tablet-portrait {
      // whatever
    }
    

    I know that Tailwind has responsive utility clases to use it inline as md:color-red but I need to abstract this breakpoins as components, as in above example.

    How should I extract Tailwind breakpoints from Tailwind config file?

  • fredrivett
    fredrivett almost 3 years
    I've found @screen md working fine in SCSS in my setup, but this solution is interesting of note as it can be used to have max-width breakpoints without changing the default breakpoint setup: @media (max-width: theme("screens.md")) { ... } (note that this is 1px off of perfect, but should work in 99.9% situations).
  • Justin L
    Justin L over 2 years
    Instead of pulling in the default theme you can use the "extend" property to allow for the extension of screen sizes... v1.tailwindcss.com/docs/breakpoints#custom-media-queries v2.tailwindcss.com/docs/… tailwindcss.com/docs/screens#adding-larger-breakpoints