Warm tip: This article is reproduced from stackoverflow.com, please click
css linear-gradients

How can I code this menu icon with only CSS and one element?

发布于 2020-03-27 10:26:16

CSS menu icon

I have tried so far.

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>
Questioner
dgknca
Viewed
12
Temani Afif 2019-07-04 04:53

Use only solid color in gradient and rely on 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>

With hover animation:

.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>

And if you want with transparency:

.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>

You were also almost good with your code but you were missing the size and the repeat:

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>

Related question to get more details about the different values: Using percentage values with background-position on a linear gradient