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

1

17

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

Methionine answered 11/1, 2023 at 6:19 Comment(0)
J
32

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'],
  }
})
Joplin answered 11/1, 2023 at 10:3 Comment(2)
For min-h-screen add ``` minHeight: { screen: ["100vh /* fallback for Opera, IE and etc. */", "100dvh"], } ```Wharfinger
This is out of date. It's not possible to pass an array in there.Massasauga

© 2022 - 2024 — McMap. All rights reserved.