如何用VW单位实现带动画元素的CSS响应式缩放且不破坏动画
To make your hamburger menu scale responsively using VW units while keeping the toggle animation intact, we just need to swap out all fixed pixel values for proportional VW units—with a key focus on maintaining the relative spacing and displacement values that make the animation work correctly.
Breakdown of Changes:
- Convert fixed dimensions to VW: Replace
width,height, andmarginof the menu lines with VW units to ensure they scale with the viewport width. - Align animation values: The original
translateY(13px)was the sum of the line height (5px) and margin (8px). We’ll use the VW equivalent of that sum to keep the rotated lines perfectly aligned into an "X" when active. - Responsive positioning: Update the sidebar’s
topandrightvalues to VW units so the menu stays consistently positioned across screen sizes.
Modified Full Code
HTML (no changes required):
<div class="slidebar" id="slide" > <div class="hamburger" id="hamburger-1" onclick="hamburger()"> <span class="line"></span> <span class="line"></span> <span class="line"></span> </div> </div>
CSS (updated with VW units):
.slidebar{ position: absolute; top: 3vw; /* Replaced fixed 17px with proportional VW */ right: 4vw; /* Replaced fixed 25px with proportional VW */ z-index: 100; transition: 0.4s ease-in-out; } .hamburger .line{ width: 5vw; /* Base responsive width */ height: 0.5vw; /* Proportional height to maintain visual ratio */ background-color: black; display: block; margin: 0.8vw auto; /* Proportional spacing between lines */ transition: all 0.3s ease-in-out; } #hamburger-1.is-active .line:nth-child(2){ opacity: 0; } .hamburger:hover{ cursor: pointer; } #hamburger-1.is-active .line:nth-child(1){ transform: translateY(1.3vw) rotate(45deg); /* Sum of margin + height: 0.8vw + 0.5vw */ } #hamburger-1.is-active .line:nth-child(3){ transform: translateY(-1.3vw) rotate(-45deg); /* Symmetric negative value for perfect alignment */ }
JavaScript (no changes required):
function hamburger(){ var hamburg = document.getElementById('hamburger-1'); hamburg.classList.toggle("is-active"); var slidebar = document.getElementById("slide"); slidebar.classList.toggle("is-active"); }
Quick Tips:
- Adjust the base
width: 5vwvalue to make the menu larger or smaller across all screen sizes—all other values will scale proportionally automatically. - If you need support for older browsers, you can re-add the vendor prefixes (
-webkit-,-ms-,-o-) to thetransitionandtransformproperties using the same VW values.
内容的提问来源于stack exchange,提问作者Hexley21
相关产品推荐
相关产品推荐

