前言
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还可以实现更多有趣的效果,例如侧导航栏、轮播图等。但是目前浏览器对该伪类的支持还不是很好,可以在不兼容老版本浏览器的情况下使用。
最后推荐一下低代码平台我的应用,可以直接去下载后私有化部署且完全免费。开源不易,望多多支持,也可通过平台提出宝贵意见,感谢!