如何用css画一个梯形

5,672 阅读1分钟

今天在工作的时候,产品要求一个梯形的展开收起按钮。

实现方法:

1.利用border构建梯形

<body>
<div class="box"></div>
</body>

<style>       
      .box{         
        width: 100px;     
        border-bottom: 100px solid red;                
        border-top: 100px solid transparent;  
        border-left: 50px solid transparent;          
        border-right: 50px solid transparent;      
           }   
 </style>

效果:

原理就不用多说了,以前画三角形也是类似的。

2.利用transform构建梯形

 <style>      
  .box{         
    width: 80px;     
    height: 180px;     
    background: red;         
    transform: perspective(0.5em) rotateY(-3deg);    
    }        
     </style>

效果:

perspective

perspective 属性定义 3D 元素距视图的距离,以像素计。
该属性允许您改变 3D 元素查看 3D 元素的视图。
当为元素定义 perspective 属性时,其子元素会获得透视效果,而不是元素本身。

原理就是通过设置perspective开启图像透视功能,加上rotateY属性进行旋转,从视觉上呈现出就是一个梯形了。

如果又文字但是不想文字跟着旋转的话,可以简单通过::before伪元素实现:

  .box {          
 width: 80px;           
 height: 180px;          
 color: white;           
 position: relative;           
 display: flex;           
 align-items: center;            
 justify-content: center;      
  }

.box::before {     
    content: "";   
    position: absolute;    
    left: 0;      
    right: 0;     
    top: 0;   
    bottom: 0;     
    z-index: -1;     
    background-color: #1890ff;    
    transform: perspective(.5em) rotateY(-2deg) ;   
    box-shadow: 0 0 7px #666;
        }

效果:

暂时就记录这两种方法,有更简便的方法欢迎评论补充。