首页 > 解决方案 > CSS 使用 div 作为掩码

问题描述

因此,我一直在尝试使用由 3 个堆叠的 div 标签制作的汉堡菜单作为具有颜色渐变的背景的遮罩(红色/黄色,蓝色/紫色是主要背景)。我想达到的结果是:结果 我知道我可以简单地使用汉堡包的 svg 文件,但我想用我制作的 div 标签来做这个,这样我以后可以为它们设置动画以转换为 ax 图标,如这整件事就是创建一个侧边栏。

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>

标签: htmlcss

解决方案


给它们相同的背景并使用位置来创建效果:

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>

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

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>


推荐阅读