首页 > 解决方案 > 如何弯曲 CSS 伪元素背景?

问题描述

我有一个红色的伪元素,我将它添加到我网站上某些部分的背景中。

一切正常,但我想把它从直线改为曲线。

知道怎么做吗?

.top-section:before {
    opacity: .7;
    content: '';
    position: absolute;
    width: 100%;
    height: 600px;
    margin-top: 12rem;
    transform: skewY(20deg);
    background: linear-gradient(-20deg,#fff 0,#fff 67%,red 100%);
    z-index: -1;
}
<div class="top-section">
<div class="inner-section">

</div>
</div>

标签: csspseudo-element

解决方案


一种方法是使用自定义 svg 创建一个clip-path来转换伪元素:

body {
  margin: 0
}

.top-section:before {
  opacity: .7;
  content: '';
  position: absolute;
  width: 100%;
  height: 600px;
  margin-top: 12rem;
  clip-path: url(#svgPath);
  background: linear-gradient(-20deg, #fff 0, #fff 67%, red 100%);
  z-index: -1;
}
<div class="top-section">
  <div class="inner-section">

  </div>
</div>

<!--svg mask-->
<svg height="0" width="0">
    <defs>
        <clipPath id="svgPath" clipPathUnits="objectBoundingBox">
            <path d='M1,1c-0.43,0-0.69-0.055-1-0.246V0c0.362,0.213,0.573,0.252,1,0.226V1z'/>
        </clipPath>
    </defs>
</svg>


推荐阅读