Svg响应宽度,高度可调

时间:2017-06-13 09:07:00

标签: css svg

一直很难找到一个好的解决方案来获得一个响应式svg,它将采用屏幕宽度加上可调高度。我尝试设置width to 100% and height to something like 200px,但没有运气。



header.svg {
  width: 100%;
  max-height: 200px;
  height: 200px;
}

<header>
<svg width="321px" height="141px" viewBox="0 0 321 141" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="header-copy-" fill="#262626">
            <g id="header-copy-2">
                <path d="M0,0.31823636 L321,0.31823636 L321,132.556396 C267.894961,138.185465 214.394961,141 160.5,141 C106.605039,141 53.1050387,138.185465 0,132.556396 L0,0.31823636 Z" id="Rectangle-Copy-12"></path>
            </g>
        </g>
    </g>
</svg>
</header>
&#13;
&#13;
&#13;

我还尝试在标题元素中添加100%宽度。

1 个答案:

答案 0 :(得分:3)

首先,您的选择器不正确,应该是header svg而不是header.svg。 SVG是标题的子项...标题没有.svg的类。

其次,我建议从SVG中删除高度和宽度。由于您设置了适当的viewbox

,因此不需要它

现在,您似乎希望SVG的宽度为页面的100%,但将高度限制为设定值。

要执行此操作,您必须将SVG的preserveAspectRatio属性设置为none

Viewbox & PreserveAspectRatio

&#13;
&#13;
header {
  background: pink;
}

svg {
  max-height: 100px;
  width: 100%;
  margin: auto;
  display: block;
}
&#13;
<header class="wide">
  <svg viewBox="0 0 321 141" version="1.1" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none">
    <defs></defs>
    <g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
        <g id="header-copy-" fill="#262626">
            <g id="header-copy-2">
                <path d="M0,0.31823636 L321,0.31823636 L321,132.556396 C267.894961,138.185465 214.394961,141 160.5,141 C106.605039,141 53.1050387,138.185465 0,132.556396 L0,0.31823636 Z" id="Rectangle-Copy-12"></path>
            </g>
        </g>
    </g>
</svg>
</header>
&#13;
&#13;
&#13;