SVG路径元素尺寸与位置超出父SVG视口问题求助
解决内联SVG路径超出父容器视口的问题
你的核心问题很明确:SVG设置了viewBox="0 0 24 24"的视口范围,但内部path的坐标数值(x最高到392、y最高到469)远大于这个视口,导致路径完全显示在SVG可视区域之外。
两种可行的解决方法:
方法1:调整SVG的viewBox匹配路径实际尺寸
直接修改SVG的viewBox为能覆盖整个path的范围,SVG会自动缩放适配你设置的h-3 w-3尺寸。根据path的坐标范围,我们可以把viewBox设为0 0 400 470(覆盖path的最大x、y值):
import React from "react"; import "./styles.css"; import "./styles/tailwind-pre-build.css"; export default function App() { return ( <div className="mr-1 flex h-5 w-5 items-center justify-center rounded-sm bg-black hover:bg-coral"> <svg className="h-3 w-3 fill-current stroke-white" viewBox="0 0 400 470" > <path stroke="#fff" strokeWidth="1.5" d="m244 84 11.1 12 12-11.98C300.6 51.37 347 36.51 392.6 44.1c68.9 11.48 119.4 71.1 119.4 141v5.8c0 41.5-17.2 81.2-47.6 109.5L283.7 469.1c-7.5 7-17.4 10.9-27.7 10.9s-20.2-3.9-27.7-10.9L47.59 300.4C17.23 272.1 0 232.4 0 190.9v-5.8c0-69.9 50.52-129.52 119.4-141 44.7-7.59 92 7.27 124.6 39.9-.9 0 0 .01 0 0zm11.1 79.9-45-46.8c-21.7-20.82-52.5-30.7-82.8-25.66C81.55 99.07 48 138.7 48 185.1v5.8c0 28.2 11.71 55.2 32.34 74.4L256 429.3l175.7-164c20.6-19.2 32.3-46.2 32.3-74.4v-5.8c0-46.4-33.6-86.03-79.3-93.66-30.3-5.04-61.1 4.84-82.8 25.66l-46.8 46.8z" /> </svg> </div> ); }
方法2:缩放路径到SVG视口范围内
如果不想修改viewBox,可以给path添加transform属性,将其缩小并平移到24x24的视口内。计算缩放比例后,设置变换参数让路径居中:
import React from "react"; import "./styles.css"; import "./styles/tailwind-pre-build.css"; export default function App() { return ( <div className="mr-1 flex h-5 w-5 items-center justify-center rounded-sm bg-black hover:bg-coral"> <svg className="h-3 w-3 fill-current stroke-white" viewBox="0 0 24 24" > <path stroke="#fff" strokeWidth="1.5" transform="scale(0.05) translate(-200, -235)" d="m244 84 11.1 12 12-11.98C300.6 51.37 347 36.51 392.6 44.1c68.9 11.48 119.4 71.1 119.4 141v5.8c0 41.5-17.2 81.2-47.6 109.5L283.7 469.1c-7.5 7-17.4 10.9-27.7 10.9s-20.2-3.9-27.7-10.9L47.59 300.4C17.23 272.1 0 232.4 0 190.9v-5.8c0-69.9 50.52-129.52 119.4-141 44.7-7.59 92 7.27 124.6 39.9-.9 0 0 .01 0 0zm11.1 79.9-45-46.8c-21.7-20.82-52.5-30.7-82.8-25.66C81.55 99.07 48 138.7 48 185.1v5.8c0 28.2 11.71 55.2 32.34 74.4L256 429.3l175.7-164c20.6-19.2 32.3-46.2 32.3-74.4v-5.8c0-46.4-33.6-86.03-79.3-93.66-30.3-5.04-61.1 4.84-82.8 25.66l-46.8 46.8z" /> </svg> </div> ); }
两种方法都能让路径正确显示在黑色方块内,第一种方法无需计算变换参数,更简洁,推荐优先使用。
内容的提问来源于stack exchange,提问作者wuiiz93
相关产品推荐
相关产品推荐

