Search code examples
csstailwind-css

Tailwind CSS fallback for new screen length types such as "lvh", "svh"


I wrote tailwind.config.js as belows to use new css length types such as "lvh", "svh".

module.exports = {
  theme: {
    extend: {
      height: {
        "screen": "100dvh",
        "screen-small": "100svh",
        "screen-large": "100lvh"
      }
    }
  }
}

then it successfully exports

.h-screen {
    height: 100dvh;
}

But I want to get with fallback properties like

.h-screen {
  height: 100vh; /* fallback for Opera, IE and etc. */
  height: 100dvh;
}

Is there any nice way to export fallback properties with Tailwind CSS?

I had no idea to try


Solution

  • Pass an array as property

    module.exports = {
      theme: {
        extend: {
          height: {
            screen: ['100vh /* fallback for Opera, IE and etc. */', '100dvh'],
          }
        }
      }
    }
    

    This will generate

    .h-screen {
      height: 100vh /* fallback for Opera, IE and etc. */;
      height: 100dvh;
    }
    

    DEMO

    Note: I'm not 100% sure it is supposed way to do it as editor shows error because we are passing not string but array of strings.

    Another way is to create utility with layer

    @layer utilities {
      .h-my-screen {
        height: 100vh; /* fallback for Opera, IE and etc. */
        height: 100dvh;
      }
    }
    

    In case if you wish to use reserved h-screen name approach is similar but it will stack default (100vh) and new value (100dvh) in correct order you need - but it is just coincidence

    @layer utilities {
      .h-screen {
        height: 100dvh;
      }
    }
    

    Same thing using Tailwind plugin

    const plugin = require('tailwindcss/plugin')
    
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      // ...
    
      plugins: [
        plugin(function ({ addBase, addComponents, addUtilities, theme }) {
          addUtilities({
            '.h-screen': {
              height: '100dvh',
            }
          })
        })
      ],
    }
    

    Created both way utility h-screen will now generate

    .h-screen {
      height: 100vh;
      height: 100dvh;
    }
    

    Note: when using JS syntax object CANNOT contain similar keys (height in your case) but it may accept an array of values in defined order

    // Wrong
    addUtilities({
      '.h-my-screen': {
        height: '100vh /* fallback for Opera, IE and etc. */',
        height: '100dvh',
      }
    })
    
    // Correct
    addUtilities({
      '.h-my-screen': {
        height: ['100vh /* fallback for Opera, IE and etc. */', '100dvh'],
      }
    })