Target mobile only breakpoint

Viewed 1240

I'm using Tailwind v3.

I have a custom background color being applied in an inline style with javascript:

<div style="background-color: RANDOM_GENERATED_COLOR" />

However in mobile breakpoint, I want it to ignore this background color, I want no background. So what I did was add !bg-transparent, using the "!" modifier I make it override the inline style:

<div style="background-color: RANDOM_GENERATED_COLOR" class="!bg-transparent" />

However I don't want the inline style overriden at all other breakpoints sm and above.

Is it possible to target !bg-transparent to mobile only breakpoint?

1 Answers

You may add custom variant which will apply styles on mobile screens only like @media max-width: 640px. Generally speaking with custom variants you can add any extra medias or state you need

const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    plugin(function ({ addVariant }) {
      addVariant('mobile-only', "@media screen and (max-width: theme('screens.sm'))"); // instead of hard-coded 640px use sm breakpoint value from config. Or anything
    }),
  ],
}
<div style="background-color: RANDOM_GENERATED_COLOR" class="mobile-only:!bg-transparent" />

It is still required to use !important flag because of inline style

Colored DEMO - resize demo screen at right

Update: Noitidart suggested another way of doing this with CSS variables - which is much cleaner and no need in !important

module.exports = {
  theme: {
    extend: {
      colors: {
        shading: 'var(--shading)'
      }
    }
  },
}
<div style="--shading: RANDOM_GENERATED_COLOR;" class="bg-shading sm:bg-transparent">
</div>

DEMO

Related