【问题标题】:How to scale inline SVG to parent containers width and height automatically?如何将内联 SVG 自动缩放到父容器的宽度和高度?
【发布时间】:2017-07-17 12:46:11
【问题描述】:

我正在尝试使用 svg 构建一个波浪形盒子。像这样的:

我已经在矢量应用程序中绘制了它,并将文档的大小设置为 500 x 200。现在,我将 SVG 内容复制到内联 SVG 标记中。因此,整体标记如下所示:

<div class="hero-wave">
    <svg width="100%" height="100%" viewBox="0 0 500 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <g fill="none" fill-rule="evenodd">
            <path d="M0,0.8828125 C0,0.8828125 21.5375284,2.70107724 30.175,8.11815895 C70.4419893,33.3720274 173.689709,104.747595 239.525,104.747595 C306.457042,104.747595 408.933103,43.7500826 451.921875,21.6893757 C494.910647,-0.371331192 500,8.11815895 500,8.11815895 L500,200.882812 L0,200.882812 L0,0.8828125 Z" id="Rectangle" fill="#595CA5"></path>
        </g>
    </svg>
</div>

当我添加宽度和高度属性时,SVG 看起来非常小,但我希望插图缩放到容器的宽度。 hero-wave div 的 css 如下所示

.hero-wave {
    position: absolute;
    bottom: 20px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 20%;
}

我怎样才能使 SVG 完全适合容器,而不会溢出。当我从 SVG 中删除 width 和 height 属性时,我得到了一个非常大的插图版本,并且底部不断溢出:

我怎样才能使 SVG 适合该灰色区域而不会溢出(灰色区域是英雄波容器)?

我对 SVG 非常陌生,我找不到任何指南来解释 SVG 在调整大小方面的工作原理。他们是否试图保持纵横比?如果有人能在这件事上对我有所了解,我将不胜感激。

编辑:如果我使纵横比相同,插图仍然会溢出父容器。

【问题讨论】:

  • 有了这样一个简单的形状,我敢肯定你可以使用 css 形状而不是 svg,它可以按百分比缩放到你的容器。

标签: html css svg


【解决方案1】:

您可以为此在svg:not(:root) 选择器中设置width: 100%height: auto。检查下面更新的 sn-p。

.hero-wave {
    position: absolute;
    bottom: 20px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 20%;
}
svg:not(:root) {
    width:100%;
    height: auto;
}
<div class="hero-wave">
    <svg width="100%" height="100%" viewBox="0 0 500 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <g fill="none" fill-rule="evenodd">
            <path d="M0,0.8828125 C0,0.8828125 21.5375284,2.70107724 30.175,8.11815895 C70.4419893,33.3720274 173.689709,104.747595 239.525,104.747595 C306.457042,104.747595 408.933103,43.7500826 451.921875,21.6893757 C494.910647,-0.371331192 500,8.11815895 500,8.11815895 L500,200.882812 L0,200.882812 L0,0.8828125 Z" id="Rectangle" fill="#595CA5"></path>
        </g>
    </svg>
</div>

【讨论】:

  • 你能解释一下它为什么有效吗? (:root) 是什么意思?为什么将高度设置为 auto 会突然变得合适?
  • 这意味着如果它不是根元素,则将 css 分配给svg 元素。
  • @Gasim 检查 sn-p 的答案,这里工作正常
  • @clayRay 在 chrome 和 firefox 中运行良好,请检查给定的 sn-p
  • svg:not (:root ) 不能有空格(无论如何对于 webpack),即svg:not(:root ) - 由于最低编辑要求,我无法编辑帖子!
猜你喜欢
  • 2014-07-31
  • 2013-11-26
  • 1970-01-01
  • 2015-09-23
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
相关资源
最近更新 更多