【问题标题】:Scale SVG along other content with CSS flexbox使用 CSS flexbox 沿其他内容缩放 SVG
【发布时间】:2020-02-07 00:27:44
【问题描述】:

我想在两个垂直对齐的 DIV 之间显示一个矩形 SVG,以便 SVG 占用尽可能多的空间(但保持其纵横比)。由于 SVG 本身是动态生成的,我必须使用 <svg> HTML 标签来包含它(即不能使用 <img> 标签)。

所以我尝试使用 flexbox,但是 SVG 不遵守规则并且变得太大:

html, body, .parent {
  height: 100%;
}

.parent {
  display: flex;
  flex-flow: column nowrap;
}

.contentSVG {
  flex-grow: 1;
}
<div class="parent">
  <div class="contentA">
    content A
  </div>
  <div class="contentSVG">
    <!-- arbritrary SVG -->
    <svg viewBox="0 0 10 10">
      <circle cx="5" cy="5" r="5" fill="red" />
    </svg>
  </div>
  <div class="contentB">
    content B
  </div>
</div>

如果我将 SVG 替换为其他内容,该示例将按预期工作。

你知道我如何在不涉及任何 JS 的情况下实现这一点吗?

【问题讨论】:

  • 请为[class ^="content"]添加边框以了解会发生什么。所有这些 div 都与窗口一样宽,并且 svg 将占用所有可用的宽度。我想你需要给[class ^="content"] 一个宽度

标签: html css svg flexbox


【解决方案1】:

您需要将width:100%;height:100% 添加到SVG 并将min-height:0 添加到父to allow the shrink effect

html, body, .parent {
  height: 100%;
  margin:0;
}

.parent {
  display: flex;
  flex-flow: column nowrap;
}

.contentSVG {
  flex-grow: 1;
  min-height:0;
}
svg {
  width:100%;
  height:100%;
}
<div class="parent">
  <div class="contentA">
    content A
  </div>
  <div class="contentSVG">
    <!-- arbritrary SVG -->
    <svg viewBox="0 0 10 10">
      <circle cx="5" cy="5" r="5" fill="red" />
    </svg>
  </div>
  <div class="contentB">
    content B
  </div>
</div>

【讨论】:

  • 有什么方法可以让您(否则很好)答案与 Apple Safari(iOS 和桌面)一起工作?目前,缩小比例不适用于最新版本。
  • @muffel 你遇到了什么问题?
  • 虽然contentSVG div 正确缩小(可以通过例如设置背景颜色进行可视化),但 SVG 本身会超出其边界:postimg.cc/Zv5tKQfB
  • @muffel 这是由于 height:100% 未正确解决。而不是将display:flex 添加到.contentSVG 。它会使元素默认拉伸,相当于 height:100%
  • 谢谢,但我无法让它工作。如果我将display:flex 添加到.contentSVG,则SVG 的高度和宽度为0。也许我错了,您能否按照您的意思将此更改添加到您的答案中?
猜你喜欢
  • 2020-10-22
  • 2020-10-21
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 2019-05-10
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多