可调高度的响应式SVG宽度

4

我一直在努力寻找一个好的解决方案,使得SVG图形能够响应屏幕宽度并且高度可调。我尝试将width设置为100%,height设置为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>

我也尝试将头部元素的宽度设为100%
1个回答

5
首先,您的选择器不正确,应该是header svg而不是header.svg。SVG是标题的子元素...标题没有.svg类。
其次,建议您从SVG中删除高度和宽度。由于您已经设置了适当的viewbox,因此不需要这样做。
现在,似乎您想要SVG的宽度占页面的100%,但高度限制为一定的值。
要实现这一点,您将必须将SVG的preserveAspectRatio属性设置为noneViewbox & PreserveAspectRatio

header {
  background: pink;
}

svg {
  max-height: 100px;
  width: 100%;
  margin: auto;
  display: block;
}
<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>


太棒了!我注意到你刚刚删除了SVG的内联样式。 - claudios
...并添加了 preserveaspectratio:none ...这很重要。 - Paulie_D
谢谢!只是好奇,你是如何设置高度的? - claudios
SVG将尽可能地扩展,因此我在其上设置了max-height。它就在CSS中。 - Paulie_D
太棒了!我现在明白了。 - claudios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接