You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用VW单位实现带动画元素的CSS响应式缩放且不破坏动画

Solution: Responsive Hamburger Menu with VW Units (No Animation Breakage)

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, and margin of 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 top and right values 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: 5vw value 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 the transition and transform properties using the same VW values.

内容的提问来源于stack exchange,提问作者Hexley21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:38:10