進階版css點選按鈕動畫
阿新 • • 發佈:2022-03-27
1. html
<div class="menu-wrap"> <input type="checkbox" class="toggler"> <div class="hamburger"><div></div></div> <div class="menu"> <div> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Serices</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> </div>
2. css
.menu-wrap { position: fixed; top: 0; left: 0; z-index: 1; } .menu-wrap .toggler { position: absolute; top: 0; left: 0; z-index: 2; /* 控制游標的型別 */ cursor: pointer; width: 60px; height: 60px; opacity: 0; } .menu-wrap .hamburger { position: absolute; top: 0; left: 0; z-index: 1; width: 60px; height: 60px; padding: 1rem; background: var(--primary--color); display: flex; justify-content: center; align-content: center; } /* hamburger line */ .menu-wrap .hamburger > div { position: relative; top: 15px; flex: none; width: 100%; height: 2px; background: #fff; transition: all 0.4s ease; } /* hamburger liner -- top & bottom */ .menu-wrap .hamburger > div:before, .menu-wrap .hamburger > div:after{ content: ''; position: absolute; z-index: 1; background: #fff; width: 100%; height: 2px; top: -10px; } .menu-wrap .hamburger > div:after { top: 10px; } /* toggler animation */ .menu-wrap .toggler:checked + .hamburger > div { transform: rotate(135deg); } /* turn linex into */ .menu-wrap .toggler:checked + .hamburger > div:before, .menu-wrap .toggler:checked + .hamburger > div:after{ top: 0px; transform: rotate(90deg); } .menu-wrap .toggler:checked:hover + .hamburger > div { transform: rotate(225deg); }
3 . 重點
:checked 選擇器匹配每個已被選中的 input 元素(只用於單選按鈕和複選框)。