请问css怎么实现这样直角梯形的tab按钮?

新手上路,请多包涵

image.png
image.png
类似于这种 tab按钮切换卡

阅读 4.6k
2 个回答

首先你要先实现两个梯形的效果,然后再通过margin负值,或者translateX或者left改变元素的位置。

为了实现层叠效果,所以,position:relative;或者position:absolute还是需要有的,同时在激活的那个 tab 上,要把 z-index 值加大。

以上是基本的思路,至于实现梯形的图形,可以直接使用这个工具:https://csstrick.alipay.com/trick/trapezoidal

image.png

细看了一下你的设计稿,梯形带有圆角效果,如果你对于 CSS 的渐变掌握不深的话,可以考虑直接使用图片来实现,简单快捷。

https://jsrun.net/JHFKp

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>梯形tab按钮-基于clip-path path函数实现</title>
  <style>
    .wrap {
      background-color: #eee;
      width: 375px;
      margin: 0 auto;
      padding: 10px;
    }

    .tabs {
      display: flex;
      width: 100%;
      overflow: hidden;
      border-radius: 8px 8px 0 0;
      background: linear-gradient(#cdd9fe, #e2e9fd);
    }

    .tab {
      flex: 0 0 50.1%;
      height: 50px;
      cursor: pointer;
      position: relative;
      text-align: center;
      line-height: 50px;
    }

    .tab.active {
      background-color: #fff;
      color: #4185ef;
    }

    .tab.active:before {
      content: '';
      position: absolute;
      top: 0;
      left: -50px;
      height: 100%;
      width: 50px;
      z-index: 2;
      background-color: #fff;
      clip-path: path('M 0,50 C 25,50 25,0 50,0 L 50, 50 Z');
    }

    .tab.active:after {
      content: '';
      position: absolute;
      top: 0;
      right: -50px;
      height: 100%;
      width: 50px;
      z-index: 2;
      background-color: #fff;
      clip-path: path('M 0,0 C 25,0 25,50 50,50 L 0, 50 Z');
    }

    .content-wrap {
      min-height: 200px;
      background-color: #fff;
    }

    
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/alpinejs/3.10.3/cdn.min.js" defer></script>
  <script src="https://unpkg.com/@unocss/runtime"></script>
  <script>
    // pass unocss options
    window.__unocss = {
      rules: [
        // custom rules...
      ],
      presets: [
        // custom presets...
      ],
      // ...
    }
  </script>
</head>

<body>
  <div class="wrap" x-data="initData()">
    <div class="tabs">
      <template x-for="index in 2" :key="index">
        <div @click="onTabClick(index)" class="tab" :class="{ 'active': activeIndex == index }" x-text="'标签' + index">
        </div>
      </template>
    </div>
    <div class="content-wrap">
      
    </div>
  </div>

  <script>
    function initData() {
      return {
        activeIndex: 1,
        onTabClick(index) {
          this.activeIndex = index
        }
      }
    }
  </script>

</body>

</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题