Merge pull request #173 from Ranhiru/update-hamburger-button-menu

[FIX] Updated hamburger button snippet to be clearer
This commit is contained in:
Angelos Chalaris
2019-11-25 12:53:29 +02:00
committed by GitHub

View File

@ -3,62 +3,59 @@ title: Hamburger Button
tags: interactivity,beginner tags: interactivity,beginner
--- ---
This is a way to build simple hamburger button for menu bar. Displays a hamburger menu which transitions to a cross on hover.
```html ```html
<button class="hb"></button> <div class="hamburger-menu">
<div class="bar top"></div>
<div class="bar middle"></div>
<div class="bar bottom"></div>
</div>
``` ```
```css ```css
.hb, .hamburger-menu {
.hb:before, display: flex;
.hb:after { flex-direction: column;
position: relative; flex-wrap: wrap;
width: 30px; justify-content: space-between;
height: 5px; height: 2.5rem;
border: none; width: 2.5rem;
outline: none;
background-color: #333;
border-radius: 3px;
transition: 0.5s;
cursor: pointer; cursor: pointer;
} }
.hb:before, .hamburger-menu .bar {
.hb:after { height: 5px;
content: ''; background: black;
position: absolute; border-radius: 5px;
top: -7.5px; margin: 3px 0px;
left: 0; transform-origin: left;
transition: all 0.5s;
} }
.hb:after { .hamburger-menu:hover .top {
top: 7.5px;
}
.hb:hover {
background-color: transparent;
}
.hb:hover:before,
.hb:hover:after {
top: 0;
}
.hb:hover::before {
transform: rotate(45deg); transform: rotate(45deg);
} }
.hb:hover::after { .hamburger-menu:hover .middle {
opacity: 0;
}
.hamburger-menu:hover .bottom {
transform: rotate(-45deg); transform: rotate(-45deg);
} }
``` ```
#### Explanation #### Explanation
- Use a `<button>` element for the middle bar of the hamburger icon. - Use a `.hamburger-menu` container `div` which contains the top, bottom, and middle bars.
- Use the `::before` and `::after` pseudo-elements to create the top and bottom bars of the icon. - The container is set to be a flex container (`display: flex`) with `flex-direction` to be `column` and `flex-wrap` to be `wrap` (alternatively, you can set both properties by a shorthand `flex-flow: column wrap`).
- Use `position: relative` on the `<button>` and `position: absolute` on the pseudo-elements to place them appropriately. - Add distance between the bars using `justify-content: space-between`.
- Use the `:hover` pseudo-selector to rotate `:before` to `45deg` and `:after` to `-45deg` and hide the center bar using`:background-color` transparent. - The animation has 3 parts: top and bottom bars transforming to 45 degree angles (`rotate(45deg)`), and the middle bar fading away by setting `opacity: 0`.
- The `transform-origin` is set to `left` so the bars rotate around the left point.
- Set `transition all 0.5s` so that both `transform` and `opacity` properties are animated for half a second.
#### Browser support #### Browser support
- https://caniuse.com/#feat=flexbox
- https://caniuse.com/#feat=css-transitions