CSS+DIV设置不规则图形--双梯形标题

1 HTML代码

// ... 无关代码省略
      <div class="title-box">
        <div class="title-content">
          <div class="title-external">
            <div class="title-inner">
            </div>
          </div>
          <div class="title-text">{{ $store.getters.getTitle }}</div>
        </div>
      </div>
      
// ... 无关代码省略
1
2
3
4
5
6
7
8
9
10
11
12

2 CSS代码

// ... 无关代码省略

    .title-box {
      // 容器div,用来布局标题居中的容器
      background-color: transparent;
      position: absolute; // 内部居中的关键代码
      display: flex;
      width: 100%;
      height: 62px;
      // 防溢出
      overflow: hidden;

      .title-content {
        // 标题容器DIV,相对于title-box居中
        background-color: transparent;
        position: relative; // 关键,不能少
        margin: 0 auto; // 居中的关键代码
        width: 400px;
        height: 100%;
      }

      .title-external {
        外梯形div容器,里面的参数根据实际情况调整
        position: absolute;
        z-index: 4;
        height: 60px;
        width: 400px;
        margin: 0 auto;
        // top: -5px;

        &::before {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          z-index: -1;
          border: 0px solid;
          border-bottom: 0 solid;
          background: linear-gradient(90deg,
              rgba(21, 103, 171, 0.25) 0%,
              rgba(0, 144, 255, 0.5) 50.43%,
              rgba(21, 105, 172, 0.25) 100%);
          ;
          // 设置梯形的关键代码,rotate中正负数分别为上下梯形,可改动查看效果
          transform: perspective(20px) rotateX(-7deg);
        }

      }

      .title-inner {
        position: absolute;
        z-index: 4;
        height: 60px;
        width: 400px;
        top: -10px;
        left: 0px;
        // 内梯形,相对上梯形上移10px


        &::before {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          z-index: -1;
          background: linear-gradient(140.73deg,
              rgba(12, 35, 72, 1) 0%,
              rgba(9, 11, 36, 1) 100%);
          border: 0px solid;
          border-bottom: 0 solid;
          // 关键代码,perspective设置于外梯形不一样的形状
          transform: perspective(15px) rotateX(-7deg);
        }
      }

      .title-text {
        position: absolute;
        width: 100%;
        height: 100%;
        font-size: 24px;
        text-align: center;
        line-height: 40px;
        letter-spacing: 4px;
        z-index: 5;

      }
    }


// ... 无关代码省略
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94

3 效果图

result.png