【问题标题】:SVG ViewBox Breaks HeightSVG ViewBox 打破高度
【发布时间】:2017-10-26 04:13:00
【问题描述】:

为什么在 SVG 元素上设置 viewbox 属性会弄乱高度并导致溢出?我怎样才能防止这种情况发生?

.parent {
  width: 500px;
  height: 500px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.child {
  flex-grow: 1;
  background-color: yellow;
  margin: 10px;
}
<div class="parent">
  <h1>testa</h1>
  <div class="child">
    <svg viewbox="0 0 40 40">
      <rect x="10" y="10" width="30" height="30" fill="red" />
    </svg>
  </div>
</div>

【问题讨论】:

  • 如果你想防止溢出显示你可以添加overflow-y: hidden.parent div。
  • 我希望 svg 根本不占用那么多空间,而是缩放其内容。
  • 图像也会发生这种情况,它不是 SVG 独有的,也不是 viewBox 属性的使用。
  • 如果我为 svg 元素设置了固定高度,它不会发生。但是,我希望 svg 填充父容器的剩余空间。

标签: html css svg layout flexbox


【解决方案1】:

由于您正在定义高度(通过flex-grow: 1;),您可以使用绝对定位来帮助您填充.child 的高度。

.parent {
  width: 500px;
  height: 500px;
  background-color: green;
  display: flex;
  flex-direction: column;
}

.child {
  position: relative;
  flex-grow: 1;
  background-color: yellow;
  margin: 10px;
}

svg {
  position: absolute;
  height: 100%;
  background-color: rgba( 0, 0, 0, 0.25); // <= for illustrative purposes
}
<div class="parent">
  <h1>testa</h1>
  <div class="child">
    <svg viewBox="0 0 40 40">
      <rect x="10" y="10" width="30" height="30" fill="red" />
    </svg>
  </div>
</div>

我相信有一个 object-fit 解决方案,但浏览器支持可能不是您需要的。

【讨论】:

    猜你喜欢
    • 2018-11-06
    • 1970-01-01
    • 2017-11-03
    • 2016-11-20
    • 2012-07-25
    • 2014-12-03
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多