如何使用CSS剪切路径属性设置自定义形状的背景?

时间:2018-09-01 03:16:43

标签: html css css3 clip-path

我正在努力使用clip-path属性来创建抽象背景,并且我不想使用图像或svg文件,因此尝试使用该属性,但无法实现以下结果: enter image description here

我的基本代码:

.bg{
  height: 100vh;
    margin: 0;
}
.shape-1{
     -webkit-clip-path: polygon(0 0, 10% 45%, 100% 0);
    clip-path: polygon(0 10%, 40% 36%, 100% 0);
    background:  #3e19c6;
    height: 100%;
    width: 100%;
    position: absolute;
    margin: 0;
    z-index: -1; 
}


.shape-2{
  -webkit-clip-path: polygon(0 62%, 100% 21%, 100% 100%, 0% 100%);
    clip-path: polygon(0 62%, 90% 21%, 100% 100%, 0% 85%);
background:  #c61951;
height: 100%;
width: 100%;
position: absolute;
margin: 0;
z-index: -1;   
}
<div class="bg">
    <div class="shape-1">    </div>
    <div class="shape-2">    </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以考虑多个背景和渐变并且仅使用一个元素来实现此目的。它也会响应:

body {
 margin:0;
 height:100vh;
 background:
  linear-gradient(to top left,transparent 49.5%, #3e19c6 50%) top/100% 30%,
  linear-gradient(to bottom right,transparent 49.5%, #c61951 50%) 0 30%/100% 30%,
  linear-gradient(#c61951,#c61951) bottom/100% 49.1%;
  
 background-repeat:no-repeat;
}

这是带有偏斜变换和伪元素的另一个想法:

body {
 margin:0;
 height:100vh;
 position:relative;
 overflow:hidden;
}
body::before,
body::after {
  content:"";
  position:absolute;
  left:0;
  width:100%;
  transform-origin:right;
  transform:skewY(-8deg);

}

body::before {
  bottom:100%;
  height:100vh;
  background:#3e19c6;
}

body::after {
  bottom:0;
  height:80%;
  background:#c61951;
}

这是clip-path解决方案:

body {
 margin:0;
 height:100vh;
 position:relative;
 overflow:hidden;
}
body::before,
body::after {
  content:"";
  position:absolute;
  left:0;
  width:100%;

}

body::before {
  top:0;
  height:25%;
  background:#3e19c6;
  -webkit-clip-path:polygon(0 0,100% 0,0 100%);
  clip-path:polygon(0 0,100% 0,0 100%);
}

body::after {
  bottom:0;
  height:75%;
  background:#c61951;
  -webkit-clip-path:polygon(0% 33.33%,100% 0,100% 100%,0 100%);
  clip-path:polygon(0% 33.33%,100% 0,100% 100%,0 100%);
}