CSS使用div作为遮罩

时间:2020-04-18 14:53:36

标签: html css

因此,我一直在尝试使用由3个div标签堆叠而成的汉堡菜单作为具有渐变色背景的遮罩(红色/黄色,蓝色/紫色是主要背景)。 我想要达到的结果是:result 我知道我可以简单地使用汉堡包的svg文件,但是我想对制作的div标签进行此操作,以便以后可以使它们动画化以在x图标中进行过渡,因为整个过程都是创建侧边栏。

html, body {
    height: 100%;
    background: linear-gradient(-45deg, #c850c0, #4158d0);
    font-family: 'Poppins', sans-serif;
    font-size: 20px;
}

.hamburger{
    background: linear-gradient(-45deg, #faf617, #ff0000);
    width: 50px;
    height: 40px;
    position: absolute;
    top: 20px;
    padding: 1px;
    left: 20px;
}

.line{
    width: 30px;
    height: 4px;
    margin: 7px;
    border-radius: 2px;
    display: block;
    background-color: #ffffff;
}
<div class="hamburger">
    <div class="line"></div>
    <div class="line"></div>
    <div class="line"></div>
</div>

1 个答案:

答案 0 :(得分:1)

为他们提供相同的背景并发挥其位置来创造效果:

html {
  height: 100%;
  background: linear-gradient(-45deg, #c850c0, #4158d0);
}

.hamburger {
  position: absolute;
  top: 20px;
  left: 20px;
  /* add this to see that it's the same
  background: linear-gradient(-45deg, #faf617, #ff0000);  */
}

.line {
  width: 30px;
  height: 4px;
  margin: 7px;
  border-radius: 2px;
  background: linear-gradient(-45deg, #faf617, #ff0000);
  background-size:calc(100% + 2*7px) calc(100%*3 + 4*7px);
}
.line:nth-child(1) {
  background-position:-7px -7px;  /*7  = 7*1 + 0*4*/
}
.line:nth-child(2) {
  background-position:-7px -18px; /*18 = 7*2 + 1*4*/
}
.line:nth-child(3) {
  background-position:-7px -29px; /*29 = 7*3 + 2*4*/
}
<div class="hamburger">
  <div class="line"></div>
  <div class="line"></div>
  <div class="line"></div>
</div>

另一个可以将mask与伪元素一起使用的想法。诀窍是不要将位置设置为.line以使伪元素相对于汉堡包定位,然后使用mask隐藏溢出内容:

html {
  height: 100%;
  background: linear-gradient(-45deg, #c850c0, #4158d0);
}

.hamburger {
  position: absolute;
  top: 20px;
  left: 20px;
  /* add this to see that it's the same
  background: linear-gradient(-45deg, #faf617, #ff0000);  */
}

.line {
  width: 30px;
  height: 4px;
  margin: 7px;
  border-radius: 2px;
  -webkit-mask:linear-gradient(#fff,#fff);
          mask:linear-gradient(#fff,#fff);
}
.line:before {
  content:"";
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background: linear-gradient(-45deg, #faf617, #ff0000);

}
<div class="hamburger">
  <div class="line"></div>
  <div class="line"></div>
  <div class="line"></div>
</div>