SVG rect使用CSS实现响应式仅Firefox生效Chrome不兼容如何解决?
SVG响应式缩放兼容方案提问
我找到了两种可以让SVG内部元素相对于SVG父容器或SVG本身实现响应式缩放的方法(要求SVG高度始终为100%):
- 方法1:使用CSS变量修改高度
- 仅在Firefox中生效,Chrome中无效果,暂未找到原因
- 方法2:通过JS获取SVG父容器高度来修改对应高度属性
- 在Firefox和Chrome中均可以正常工作,但期望缩放逻辑统一在一处,即仅使用CSS实现
简化场景说明
我的项目中需要构建一个SVG导航按钮,外观为垂直边框加居中箭头,其中箭头尺寸固定,箭头上下的竖线长度随按钮高度变化,按钮高度为100vh - 100px,预留出各为50px的页眉和页脚空间。因此除了SVG高度外,还需要viewBox尺寸可响应,我之前判断这部分无法通过CSS实现。
现有实现方案
方案1:JS仅处理viewBox缩放(approach1.html)
完整代码如下:
<html lang="en"> <head> <title>Responsive SVG Rect</title> <link rel="shortcut icon" href="data:,"> <style> :root { --view-box-half: calc(50%); --rect-thick: calc(25px); --end-gap: calc(50px); --longer-side: calc(var(--view-box-half) - var(--end-gap)); } body { margin: 0; } rect { width: var(--rect-thick); height: var(--longer-side); } button { width: 50px; margin: var(--end-gap) 0 0 0; padding: 0; height: calc(100vh - 100px); background-color: blue; cursor: pointer; border: none; } svg { opacity: 0.7; transition: opacity 0.4s; } svg:hover { opacity: 1; } </style> <script type="module" defer> const svg = document.querySelector('svg'); const parent = svg.parentNode; // 父元素为button const rect = document.querySelector('rect'); setResponsiveArrowResizing(); function setResponsiveArrowResizing() { window.addEventListener('load', updateSizes); window.addEventListener('resize', updateSizes); function updateSizes() { updateViewBoxSize(); updateRectSize(); } function updateViewBoxSize() { // viewBox的原点(0,0)设置在SVG中心 svg.viewBox.baseVal.x = parent.offsetWidth / -2; svg.viewBox.baseVal.y = parent.offsetHeight / -2; svg.viewBox.baseVal.width = parent.offsetWidth; svg.viewBox.baseVal.height = parent.offsetHeight; } function updateRectSize() { // 矩形高度由CSS控制 } } </script> </head> <body> <button> <svg width="100%" height="100%" viewBox="0 0 0 0" style="background-color: rgb(150, 40, 40)"> <rect/> </svg> </button> </body> </html>
方案2:JS同时控制viewBox与矩形高度(approach2.html)
和approach1.html逻辑一致,仅修改两处代码,改为由JS控制rect高度而非CSS:
rect { width: var(--rect-thick); /* 注释掉CSS控制的高度规则 height: var(--longer-side); */ }
function updateRectSize() { rect.style.height = parent.offsetHeight / 2 - 50 + 'px'; }
问题
是否存在纯CSS方案,可以同时兼容Firefox和Chrome实现上述需求?
内容的提问来源于stack exchange,提问作者Daniel W. R. Hart
相关产品推荐
相关产品推荐

