案例来源
本例来自CodingStartup的视频:使用 HTML+CSS 制作动态 Hamburger Menu
学到知识
- 通过checkbox的伪类checked,来绑定菜单,实现点击checkbox实现特效。
- 使用label嵌套菜单div,并使用for属性绑定checkbox,实现点击菜单本身即可实现特效。
- 在使用transition时,要设置元素的初始状态,例如本例的top属性,否则会出现异常的效果。
- 使用transform-origin设置元素原点,表示从哪个位置进行改变。
主要代码
html
<body>
<header>
<input type="checkbox" id="toggle">
<label for="toggle">
<div class="hamburger-container">
<span></span>
<span></span>
</div>
</label>
<div class="nav-item">
<ul>
<li>Home</li>
<li>iPhone</li>
<li>iPad</li>
<li>Mac</li>
<li>TV</li>
</ul>
</div>
</header>
</body>
css
#toggle {
display: none;
}
.hamburger-container {
display: block;
width: 20px;
height: 20px;
position: relative;
top: 16px;
}
.hamburger-container span {
display: block;
height: 1px;
background-color: #fff;
position: relative;
transition: top .3s ease-in-out .3s, transform .3s ease-in-out;
top: 0;
}
.hamburger-container span:nth-child(2) {
margin-top: 7px;
}
header {
height: 44px;
background-color: #000;
padding: 0 18px;
}
body {
margin: 0;
padding: 0;
}
#toggle:checked + label .hamburger-container span:nth-child(1) {
transform: rotate(45deg);
top: 4px;
transition: transform .3s ease-in-out .3s, top .3s ease-in-out;
}
#toggle:checked + label .hamburger-container span:nth-child(2) {
transform: rotate(-45deg);
top: -4px;
transition: transform .3s ease-in-out .3s, top .3s ease-in-out;
}
.nav-item {
background-color: rgba(0, 0, 0, .82);
width: 100%;
height: 100vh;
position: absolute;
top: 44px;
left: 0;
transform: scaleY(0);
transition: transform .3s ease-in-out, opacity .3s ease-in-out;
transform-origin: 50% 0;
opacity: 0;
}
#toggle:checked ~ .nav-item {
transform: scale(1);
opacity: 1;
}
ul {
margin-top: 1em;
}
ul li {
color: #fff;
}