css - 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 结构,它将不再有效。
我尝试过的事情:
- 在上做一个
transform: scale()
通过 CSS<rect>
- 我不知道要放入什么以scale()
使其表现得像100% - 60px
. - 更改嵌套
<svg>
元素 的宽度<svg width="calc(100% - 60px)">
不起作用 - 不能calc()
在width
属性内执行<svg width="100%" style="width: calc(100% - 60px);">
(有或没有width
属性) - 不起作用 - 无论width
属性是否存在,CSS“宽度”属性都会被忽略。
我开始认为我现在想要做的事情对于 SVG 是不可能的,但这似乎不是一个不常见的用例。有没有办法做到这一点?
解决方案
正如评论中所讨论的那样,您可能会通过将图形区域设置为 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>
推荐阅读
- ios - 如何异步下载和缓存视频以在我的应用程序中使用?
- functional-programming - 如何使用 Ramda 从 Jira API 返回整个分页集?
- .net - 等效于 `My.Settings.Reset`,但针对单个特定设置
- python - 如何根据索引向量求和
- testing - Quarkus gradle 测试失败
- sparql - 测试是否缺少模式返回匹配它的三元组
- linear-regression - 拟合回归后如何使用Seaborn的residplot?
- ios - Swift,Firebase - 将 CMSampleBufferRef 与相机的实时供稿一起使用
- python - 使用 pandas 或 csr_matrix 工作的项-项矩阵稀疏数据
- powerbi - Power Bi 刷新中的触发方式选项?