Back
A step-by-step guide on how to create a menu icon that transforms to close icon on hover.
<div class="menu_icon"> <div></div> <div></div> <div></div> </div>
.menu_icon { display: flex; flex-direction: column; row-gap: 2px; width: 8px; cursor: pointer; }Now we'll style the lines. First we'll set height for each line to 1 pixel and background color to black. Then we'll round the borders by setting border-radius to 1 pixel. And lastly, we'll add transition of 200 milliseconds so that every change on hover (that we'll set later) is smooth.
.menu_icon div { height: 1px; background-color: black; border-radius: 1px; transition: .2s; }Now we'll style all 3 lines when "menu_icon" is hovered. We'll just add transition of 200 milliseconds to each line to make upcoming changes smooth.
.menu_icon:hover div { transition: .2s; }Now we'll style the first line on "menu_icon" hover. We'll set color of this line to red by changing background-color, and we'll rotate it a bit. This line now represents half of the close button and will slowly (200ms) rotate and change it's color to red.
.menu_icon:hover div:first-child { background-color: rgb(202, 34, 0); transform: rotate(40deg) translate(2px, 2.2px); }Now we'll style the second line. We'll just set opacity to 0, to hide this element on hover.
.menu_icon:hover div:nth-child(2) { opacity: 0; }And lastly, same as on the first line, we'll set third's line background color to the same red and rotate it a bit. First and last line should slowly rotate and form X shape, while second line should disappear.
.menu_icon:hover div:last-child { background-color: rgb(202, 34, 0); transform: rotate(-40deg) translate(2px, -2.2px); }Clicking on this element should close a menu. And that's it.
<div class="menu_icon"> <div></div> <div></div> <div></div> </div> <style> .menu_icon { display: flex; flex-direction: column; row-gap: 2px; width: 8px; cursor: pointer; } .menu_icon div { height: 1px; background-color: black; border-radius: 1px; transition: .2s; } .menu_icon:hover div { transition: .2s; } .menu_icon:hover div:first-child { background-color: rgb(202, 34, 0); transform: rotate(40deg) translate(2px, 2.2px); } .menu_icon:hover div:nth-child(2) { opacity: 0; } .menu_icon:hover div:last-child { background-color: rgb(202, 34, 0); transform: rotate(-40deg) translate(2px, -2.2px); } </style>Thank you for reading this article.