使用 tailwindcss 隐藏滚动条

关注公众号:前端成长指南,查看更多文章

滚动条是浏览器的默认行为,在移动端会自动隐藏滚动条,然而 PC 上会显示默认滚动条。

如果是在 PC 页面中还是可以接受的,但是在弹框中显示一个宽宽的滚动条,就破坏了设计的美感。

当然,肯定还是要保证内容能够滚动,这里只是需要隐藏滚动条。除了隐藏滚动条,还可以对滚动条进行样式设置,这里就不介绍了。

使用 CSS

css 复制代码
/* Hide scrollbar for Chrome, Safari and Opera */
.scrollbar-hidden::-webkit-scrollbar {
  display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
.scrollbar-hidden {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

其中需要针对 Chrome、IE、Edge、Firefox 进行兼容,它们涉及的属性并不一样,webkit 内核是通过伪元素 -webkit-scrollbar 进行设置,IE 是 -ms-overflow-style,Firefox 是 scrollbar-width。

如果使用 tailwindcss,可以:

使用 utility class(推荐)

可以使用官网的 Adding custom utilities 增加自定义 utilities,写在 @tailwind 的全局文件中:

css 复制代码
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer utilities {
  /* Chrome, Safari and Opera */
  .scrollbar-hidden::-webkit-scrollbar {
    display: none;
  }

  .scrollbar-hidden {
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
  }
}

在页面中的使用:

html 复制代码
<div class="scrollbar-hidden">
  <!-- ... -->
</div>

注意 tailwindcss v4.0 已经更改了写法,直接使用 @utilities指令,具体可以参考文档。

使用 tailwind plugin

在 tailwind.config.js 中进行配置:

js 复制代码
/** @type {import('tailwindcss').Config} */

const plugin = require("tailwindcss/plugin")

module.exports = {
  plugins: [
    plugin(({ addUtilities }) => {
      addUtilities({
        /* Chrome, Safari and Opera */
        ".scrollbar-hidden::-webkit-scrollbar": {
          display: "none",
        },

        ".scrollbar-hidden": {
          "scrollbar-width": "none" /* Firefox */,
          "-ms-overflow-style": "none" /* IE and Edge */,
        },
      })
    }),
  ],
}

在页面中的使用:

html 复制代码
<div class="scrollbar-hidden">
  <!-- ... -->
</div>

使用 arbitrary values

直接在 HTML class 中定义:

html 复制代码
<div class="[&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
  <!-- ... -->
</div>

这种方式适合一次性的使用。

注意 tailwindcss 的变体(Arbitrary) 除了 Arbitrary values 还有 Arbitrary properties、Arbitrary variants。[-ms-overflow-style:none] [scrollbar-width:none] 这种用法是 Arbitrary properties,[&::-webkit-scrollbar]:hidden 这种用法是 Arbitrary variants, 表示获取当前元素伪元素 -webkit-scrollbar,当做变体条件,应用 class hidden。

使用 tailwind-scrollbar-hide

安装依赖,配置:

js 复制代码
// tailwind.config.js
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('tailwind-scrollbar-hide')
    // ...
  ]
}

使用:

html 复制代码
<div class="scrollbar-hidden">
  <!-- ... -->
</div>

参考

相关推荐
杀死一只知更鸟debug5 分钟前
vue2,vue3,vue3 + vite 动态加载图片的方式
前端·javascript·vue.js
剪刀石头布啊19 分钟前
ECMAScript、html头、dom、bom、a空链、选择器、css样式继承等、css通用属性值、文档流等
css·html
剪刀石头布啊21 分钟前
浏览器进程与事件循环
前端·浏览器
剪刀石头布啊21 分钟前
浏览器渲染原理
前端·浏览器
日记成书1 小时前
【HTML 基础教程】HTML 表格
前端·html
木木黄木木1 小时前
HTML5贪吃蛇游戏开发经验分享
前端·html·html5
无名之逆1 小时前
hyperlane:Rust HTTP 服务器开发的不二之选
服务器·开发语言·前端·后端·安全·http·rust
李鸿耀1 小时前
前端包管理工具演进史:从 npm 到 pnpm 的技术革新
前端·面试
麓殇⊙1 小时前
前端基础知识汇总
前端
MariaH1 小时前
邂逅jQuery库
前端