Search code examples
tailwind-css

How to Create Custom Responsive Spacing Classes in Tailwind CSS?


I'm working on a project using Tailwind CSS and I want to create custom spacing classes that adjust their values based on the screen size. Specifically, I want to define classes like mb-custom or py-custom that will have different spacing values depending on whether the screen is small (sm), medium (md), large (lg), or extra-large (xl).

For example, I want the mb-custom class to have:

mb-2 on small screens
mb-4 on medium screens
mb-6 on large screens
mb-8 on extra-large screens

Here's what I've tried so far in my tailwind.config.js:

module.exports = {
  theme: {
    extend: {
      spacing: {
        'custom': {
          sm: '0.5rem', // 8px
          md: '1rem',   // 16px
          lg: '1.5rem', // 24px
          xl: '2rem',   // 32px
        },
      },
    },
  },
  variants: {
    margin: ['responsive'],
  },
  plugins: [],
}

But when I try to use mb-custom, it's not applying the correct values based on the screen size.

How can I correctly define and use custom responsive spacing classes in Tailwind CSS?


Solution

  • there might be several way to achieve this, but one way which i guess is easy, is use css variable.

    your tailwind config should be like

    module.exports = {
      theme: {
        extend: {
          spacing: "var(--custom-variable)",
          },
        },
      },
      variants: {
        margin: ['responsive'],
      },
      plugins: [],
    }
    

    and in css file change the variable base on screen size

    @screen 2xl {
        :root {
            --custom-variable: 50px !important;
        }
    }
    
    @screen xl {
        :root {
            --custom-variable: 40px !important;
        }
    }
    @screen lg {
        :root {
            --custom-variable: 30px !important;
        }
    }
    @screen md {
        :root {
            --custom-variable: 20px !important;
        }
    }
    
    @screen sm {
        :root {
            --custom-variable: 10px;
        }
    }