首页 > 解决方案 > SVG 缩放 (100% - 60px)

问题描述

我正在尝试构建一个 SVG 图像,其内容是容器宽度的 100%,某些文本减去 60 像素。

如果我使用 HTML 或带有 javascript 的 SVG,我会毫无问题地这样做。但我觉得应该有一种方法可以使用 SVG(如果需要,还可以使用 CSS)。

我想要与此等效的(此处为 Codepen):

<svg width="100%" height="100%">
  <rect fill="#ccc" x="0" y="0" width="100%" height="100%"></rect>

  <text x="100%" y="50%" stroke="black" text-anchor="end">Y-axis</text>

  <svg width="100%" height="100%">
    <!-- This rect represents the entirety of the contents of the graph -->
    <rect x="0" y="0" style="width: calc(100% - 60px)" height="100%" fill="#c88"></rect>
  </svg>
</svg>

在上面的代码片段中,内部<rect>调整为100% - 60px容器元素的宽度。但是,此技巧仅适用于单个元素 - 如果您将其替换<rect>为复杂的 SVG 结构,它将不再有效。

在此处输入图像描述

我尝试过的事情:

  1. 在上做一个transform: scale()通过 CSS <rect>- 我不知道要放入什么以scale()使其表现得像100% - 60px.
  2. 更改嵌套<svg>元素 的宽度
    • <svg width="calc(100% - 60px)">不起作用 - 不能calc()width属性内执行
    • <svg width="100%" style="width: calc(100% - 60px);">(有或没有width属性) - 不起作用 - 无论width属性是否存在,CSS“宽度”属性都会被忽略。

我开始认为我现在想要做的事情对于 SVG 是不可能的,但这似乎不是一个不常见的用例。有没有办法做到这一点?

标签: csssvg

解决方案


正如评论中所讨论的那样,您可能会通过将图形区域设置为 viewBox 的 100% 来实现相同的运气,但是将 SVG 放置60px在右侧有填充的容器中以占文本空间。

将你的 text (和 background rect)移动到x="100%"它的text-anchor="start",除了让 SVG 溢出之外,你可以获得非常接近的结果而无需转换你的图形,因为你有一个60px可以始终依赖的固定值:

div {
  padding-right: 60px;
}
svg {
  overflow: visible;
}
<div>
  <svg width="100%" height="100%">
    <rect fill="#ccc" x="100%" y="0" width="60px" height="100%"></rect>

    <text x="100%" y="50%" stroke="black" text-anchor="start">Y-axis</text>

    <rect x="0" y="0" width="100%" height="100%" fill="#c88"></rect>
  </svg>
</div>

PS:也许你希望你的文本有text-anchor="middle",并在 CSS 中转换它transform: translateX(30px)以将其放置在“文本”区域的中心——这样可能看起来更干净:

div {
  padding-right: 60px;
}
svg {
  overflow: visible;
}
text {
  transform: translateX(30px);
}
<div>
  <svg width="100%" height="100%">
    <rect fill="#ccc" x="100%" y="0" width="60px" height="100%"></rect>

    <text x="100%" y="50%" stroke="black" text-anchor="middle">Y-axis</text>

    <rect x="0" y="0" width="100%" height="100%" fill="#c88"></rect>
  </svg>
</div>


推荐阅读