首页 > 解决方案 > 保持 SVG 比例,同时减小窗口(或容器)大小

问题描述

我有一个 SVG 图形,它是容器的子元素。

如果我希望它适合这个容器的整个宽度,我通常会这样做preserveAspectRatio="none"并将宽度设置为 100%(如果我想为 SVG 添加一些额外的高度,可以使用可选的高度值)。

但是,我希望它可以让 SVG 适合容器,但是当我将窗口拖动到更小的尺寸时,楔形(即 SVG 的对角线角度)保持在相同的角度,同时仍然填充容器。

在示例代码中,我保留了preserveAspectRatio=none代码以显示我想要的一般效果(不同之处当然是我希望楔形的角度在窗口尺寸减小时保持相同)。

这可能吗?我正在努力想办法让它发挥作用。

这是一个 Codepen:https ://codepen.io/emilychews/pen/pGbPby

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 4rem;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="none" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

标签: htmlsvgsizeaspect-ratio

解决方案


如果您希望 SVG 保持其纵横比,而不是拉伸,请不要使用preserveAspectRatio="none". 使用不同的preserveAspectRatio值。例如"xMinYMax slice".

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 4rem;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="xMinYMax slice" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

但是,如果页面变得足够宽以至于楔形变得如此高以至于顶部被剪掉,您显然必须决定要发生什么。例如,在您的示例(以及我上面的示例)中,您将 SVG 的高度限制为4em. 所以你只看到楔形的底部。

如果我将 SVG 高度更改为100%,您会看到更多。

body {
  margin: 0;
  padding: 0;
  display: flex;
  width: 100%;
  height: 100vh;
  justify-content: center;
  align-items: center;
}

.container {
  width: 80%;
  height: 10rem;
  background: lightblue;
  position: relative;
}

.wedge {
  width: 100%;
  left: 0;
  bottom: 0;
  height: 100%;
  position: absolute
}
<div class="container">
  <svg class="wedge" preserveAspectRatio="xMinYMax slice" aria-hidden="true" viewBox="0 0 376.9 122.7">
    <polyline fill="#000" points="376.9 122.69 0 122.35 376.55 0 376.9 122.69"/>
  </svg>
</div>

当然,您可能还想减小楔形的角度。


推荐阅读