How to change desktop-first design code to mobile-first with tailwind css (responsiveness)

69 views Asked by At

I developed a website with Html and tailwind css, now I need to make the website responsive. I just discovered that tailwind uses a mobile-first breakpoint system, meanwhile I developed mine using the desktop-first approach. Now I am confused on how to change the design into a mobile design using tailwind css, so that I can make the website responsive.

I tried changing the available styles to fit into a mobile screen size but it isn't working, rather it was scattering the whole thing.

1

There are 1 answers

0
Fernando SA On

As you said, Tailwind uses a mobile-first approach by default. These are the breakpoints defined by default in Tailwind:

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) { ... }
  '2xl': '1536px', // => @media (min-width: 1536px) { ... }
}

If you give, for instance, these classes to an element "m-0 md:m-4", the element will have a margin only when screen width is larger than 768px. You are setting the general rule for smaller screens and a specific rule for larger screens (that's why it's considered mobile-first).

You can change to a desktop-first behaviour by overriding the screens configuration in a slightly different way. Add the following to your tailwind.config.js:

module.exports = {
  /* ... other config... */
  theme: {
    /* ... other theme rules ... */
    screens: {
      '2xl': {'max': '1535px'}, // => @media (max-width: 1535px) { ... }
      'xl': {'max': '1279px'}, // => @media (max-width: 1279px) { ... }
      'lg': {'max': '1023px'}, // => @media (max-width: 1023px) { ... }
      'md': {'max': '767px'}, // => @media (max-width: 767px) { ... }
      'sm': {'max': '639px'}, // => @media (max-width: 639px) { ... }
    }
  }
}

Important: max-width breakpoints must be listed in descending order so that they override each other as expected. (see docs here)

Note we are using max widths now instead of min widths. Now, an element with class "m-0 md:m-4" will only have a margin if screen width in under 767px.

If you already styled your site for larger screens, I suggest you add the above configuration to your tailwind.config.js (you can add/remove/edit breakpoints as you wish) and start using modifiers (such as md:) for the specific styles you want to apply to smaller screens only.