温馨提示:本文翻译自stackoverflow.com,查看原文请点击:linear gradients - How can I code this menu icon with only CSS and one element?
css linear-gradients

linear gradients - 如何仅使用CSS和一个元素来编码此菜单图标?

发布于 2020-03-27 11:35:43

CSS菜单图标

到目前为止,我已经尝试过了。

body {
  margin:0;
  padding:20px;
  background-color: #000;
}

.mobil-menu__icon {
  height: 50px;
  width: 50px;
  background: 
    linear-gradient(to bottom, #fff 0%, #fff 20%, transparent 20%, transparent 100%),
    linear-gradient(to bottom, transparent 0%, transparent 40%, #fff 40%, #fff 60%, transparent 60%, transparent 100%),
    linear-gradient(to bottom, transparent 0%, transparent 80%, #fff 80%, #fff 100%);
}
<div class="mobil-menu__icon"></div>

查看更多

查看更多

提问者
dgknca
被浏览
24
Temani Afif 2019-07-04 04:53

仅在渐变中使用纯色,并依靠background-size

.mobil-menu__icon {
  height: 50px;
  width: 50px;
  background:
    /*                         position    / width height */
    linear-gradient(#fff,#fff) top    left / 100%  20%,
    linear-gradient(#fff,#fff) center left / 80%   20%,
    linear-gradient(#fff,#fff) bottom left / 60%   20%,
    red;
  border:10px solid red;
  background-repeat:no-repeat; /* Never forget this! */
}
<div class="mobil-menu__icon"></div>

使用悬停动画:

.mobil-menu__icon {
  height: 50px;
  width: 50px;
  background:
    linear-gradient(#fff,#fff) top    left,
    linear-gradient(#fff,#fff) center left,
    linear-gradient(#fff,#fff) bottom left,
    red;
  background-size:
    100% 20%,
    80%  20%,
    60%  20%;
  border:10px solid red;
  background-repeat:no-repeat;
  transition:0.3s all;
}
.mobil-menu__icon:hover {
  background-size:100% 20%;
}
<div class="mobil-menu__icon"></div>

如果您想要透明:

.mobil-menu__icon {
  height: 50px;
  width: 50px;
  background:
    linear-gradient(red,red) 0    calc(1*100%/4) / 100%  20%,
    linear-gradient(red,red) 0    calc(3*100%/4) / 100%  20%,
    
    linear-gradient(red,red) 100% calc(2*100%/4) / 20%  20%,
    linear-gradient(red,red) 100% calc(4*100%/4) / 40%  20%;
  border:10px solid red;
  background-repeat:no-repeat; 
}

body {
  background:repeating-linear-gradient(to right,white 0 5px,grey 10px);
}
<div class="mobil-menu__icon"></div>

您的代码也几乎不错,但是缺少大小和重复项:

body {
  margin: 0;
  padding: 20px;
  background-color: #000;
}

.mobil-menu__icon {
  height: 50px;
  width: 50px;
  background: 
    linear-gradient(to bottom, #fff 0%, #fff 20%, transparent 20%, transparent 100%), 
    linear-gradient(to bottom, transparent 0%, transparent 40%, #fff 40%, #fff 60%, transparent 60%, transparent 100%), 
    linear-gradient(to bottom, transparent 0%, transparent 80%, #fff 80%, #fff 100%);
   background-size:100% 100%,80% 100%, 60% 100%;
   background-repeat:no-repeat;
}
<div class="mobil-menu__icon"></div>

相关问题以获取有关不同值的更多详细信息: 使用百分比值和线性渐变的背景位置