首页 > 解决方案 > SVG 百分比坐标已关闭

问题描述

我有三个 SVG 嵌套在另一个 SVG 中。第一个应该是流动的并且是伸展preserveAspectRationone。其他两个设置为10%90%x值。但是,如果您调整页面大小,您会发现它们与左侧和右侧的距离不同。为什么?

我希望看到左边的距离与右边的距离相同。

.box {
  width: 60vw;
  border: 1px dashed lightgray;
}

svg {
  overflow: visible;
}
<div class="box">
  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="50">
    
    <svg viewBox="0 0 2 2" preserveAspectRatio="none">
      <rect x="0" width="2" height="1" fill="#DDDDDD" />
    </svg>

    <svg x="10%" viewBox="0 0 20 20" preserveAspectRatio="xMinYMid">
      <rect x="0" y="0" width="10" height="10" fill="#7FDBFF" />
    </svg>

    <svg x="90%" viewBox="0 0 20 20" preserveAspectRatio="xMinYMid">
      <rect x="0" y="0" width="10" height="10" fill="#7FDBFF" />
    </svg>
    
  </svg>
</div>

标签: htmlcsssvgresponsive

解决方案


因为您在 90% 处开始绘制第二个蓝色框,而您真的想在 90% 处结束绘制。通过将第二个蓝色框的 viewBox 设置为:

viewBox="20 0 20 20"

推荐阅读