html - 如何在不改变高度的情况下让 SVG 具有流畅的宽度?

标签 html css svg

我想完成两件事:

  1. SVG 宽度会动态缩放以占据容器宽度的 100%。

  2. 当容器的宽度发生变化时,SVG 会被拉伸(stretch)或模糊(意味着使用 svg 的路径绘制的波浪)

  3. SVG 的高度保持固定为 760 像素。目前,如果您调整容器的大小,SVG 的高度会降低,这是不需要的。

.container {
  width: 100%;
  background: green;
  height: 760px;
}

svg {
 width: 100%;
}

svg path {
 width: 100%;
}
  <div class="container">
    <svg width="1440" height="760" viewBox="0 0 1440 760" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path
        d="M677.112 54.1657C400.36 -43.9336 110.391 13.291 0 54.1657V760H1440V54.1657C1301.02 95.0404 953.865 152.265 677.112 54.1657Z"
        fill="purple"
      />
    </svg>
  </div>

最佳答案

我可能会使用 SVG 作为 div 的背景,你可以固定 div 的高度并将 background-position 调整到顶部

.container {
  width: 100%;
  background: green;
  height: 760px;
}

.container>div {
  height: 100%;
  background: 
   url('data:image/svg+xml;utf8,<svg width="1440" height="760" viewBox="0 0 1440 760" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M677.112 54.1657C400.36 -43.9336 110.391 13.291 0 54.1657V760H1440V54.1657C1301.02 95.0404 953.865 152.265 677.112 54.1657Z"  fill="purple"/></svg>') top/100% no-repeat, 
    /*cover the bottom part with the same color*/
   linear-gradient(purple, purple) bottom/ 100% calc(100% - 20vw) no-repeat;
}
<div class="container">
  <div>
  </div>
</div>

您还可以减少代码以仅保留容器:

.container {
  height: 760px;
  background: 
   url('data:image/svg+xml;utf8,<svg width="1440" height="760" viewBox="0 0 1440 760" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M677.112 54.1657C400.36 -43.9336 110.391 13.291 0 54.1657V760H1440V54.1657C1301.02 95.0404 953.865 152.265 677.112 54.1657Z"  fill="purple"/></svg>') top/100% no-repeat, 
    /*cover the bottom part with the same color*/
   linear-gradient(purple, purple) bottom/ 100% calc(100% - 20vw) no-repeat,
   green;
}
<div class="container">
</div>

关于html - 如何在不改变高度的情况下让 SVG 具有流畅的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901424/

相关文章:

css - 为什么ul对齐到底部

javascript - 如何使 JavaScript 类切换持久化

javascript - 如何使用webpack html插件在头部注入(inject)css包和在体内注入(inject)js包

javascript - D3.js - 如何使用圆环图的下拉控件创建过渡?

javascript - 如何制作响应式图像 map ,其中图像和热点会随窗口自动调整大小?

javascript - 使用 selects 和 javascript

html - CSS:随着窗口大小调整缩小div宽度但保持最大宽度?

html - 使用 dt 标签手动覆盖 import.io 的 xpath

html - 如何减少CSS中的div大小?

ios - 如何在 ios sdk 中将 svg 图像设置为按钮图像?