如何使用CSS clip-path属性设置自定义形状的背景?

问题描述 投票:3回答:1

我正在努力与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>
html css css3 clip-path
1个回答
1
投票

考虑到多个背景和渐变以及只有一个元素,您可以实现这一点。它也会响应:

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%);
}
© www.soinside.com 2019 - 2024. All rights reserved.