scroll-marker实现tab效果

前言

tab 组件是我们经常使用到的,以前实现方式大多需要借助js去动态判断当前展示的是哪个tab项,再动态渲染对应的项,若需要实现过度动画还需要比较复杂的控制。最近发现一个很好用的css属性scroll-marker可以直接实现tab效果并且还有切换动画。

效果展示

实现代码

html 部分

html部分仅需要填入内容即可,使用--tab-title变量来传递tab的标题

html 复制代码
<div class="tab">
  <div class="item" style="--tab-title: 'tab1';">tab content 1</div>

  <div class="item" style="--tab-title: 'tab2';">
    <h3>tab content 2</h3>
    <p>1212312</p>
  </div>

  <div class="item" style="--tab-title: 'tab3';">tab content 3</div>

  <div class="item" style="--tab-title: 'tab4';">tab content 4</div>
</div>

css 部分

::scroll-marker-group:伪元素,是子元素的::scroll-marker的父节点,有before和after两个值,表示该伪元素是在tab的前面还是后面

::scroll-marker:伪元素,与每一项直接关联,点击后tab会滚动到对应项的位置

:target-current:伪类,表示当前滚动的位置

css 复制代码
.tab {
  display: flex;
  flex-direction: row;
  position: relative;

  overflow: auto;
  scrollbar-width: none;
  overscroll-behavior-x: contain;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth; /** 平滑滚动 */
  scroll-marker-group: before;
}

.tab::scroll-marker-group {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  overflow-x: auto;
  scrollbar-width: none;
  height: 36px;
  line-height: 36px;
  width: 100%;
  border-bottom: 1px solid #ccc;
}

.tab .item {
  scroll-snap-align: start;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.tab .item::scroll-marker {
  display: inline-block;
  content: var(--tab-title);
  text-decoration: none;
  color: #333;
  padding: 0 8px;
  height: 34px;
  line-height: 34px;
  border-bottom: 2px solid transparent;
}

.tab .item::scroll-marker:hover {
  color: #409eff;
}

.tab .item::scroll-marker:target-current {
  color: #409eff;
  border-color: #409eff;
}

总结

利用scroll-marker还可以实现更多有趣的效果,例如侧导航栏、轮播图等。但是目前浏览器对该伪类的支持还不是很好,可以在不兼容老版本浏览器的情况下使用。

最后推荐一下低代码平台我的应用,可以直接去下载后私有化部署且完全免费。开源不易,望多多支持,也可通过平台提出宝贵意见,感谢!

相关推荐
程序员爱钓鱼几秒前
Rust Option 详解:安全处理“可能存在,也可能不存在”的值
前端·后端·rust
程序员爱钓鱼1 分钟前
Go Modules 包管理详解:go.mod、go.sum 与依赖管理
前端·后端·go
qq_589666058 小时前
TypeScript 完整入门教程
前端·javascript·typescript
用户0595401744612 小时前
LLM对话记忆测试踩坑实录:手工回归30分钟,自动化后2分钟发现3个隐藏Bug
前端·css
Ashley的成长之路13 小时前
前端性能优化实战手册·第2篇:资源加载策略全解
前端·性能优化·资源加载·http/3·性能优化实战·资源加载优化
浅水壁虎13 小时前
vue基础(第二章 )
前端·javascript·vue.js
界面开发小八哥13 小时前
界面控件DevExtreme v26.1新版亮点——支持Angular 22
前端·javascript·angular.js·devexpress·ui开发·devextreme
Getflare13 小时前
前端 + UI 设计 + AI:这不是三个工种,是一个新三角能力模型(附自检清单)
前端·人工智能·ui
oil欧哟13 小时前
我做了一个 Vibe Coding 术语学习站:VibeHub
前端·ai·agent·独立开发·vibe coding