【问题标题】:Center large svg in container在容器中居中大 svg
【发布时间】:2017-09-16 06:19:05
【问题描述】:

我试图将一个大的 svg 放在一个容器 div 中,同时最大化 svg 的大小并保持纵横比。

由于某种原因,svg显示正确,但是width和height属性不正确,好像svg扩展成整个父级。

我怎样才能使 svg 具有正确的大小?

请,这应该只用 CSS 解决,不要用 javascript。

另外,请注意,如果我将 svg 替换为大图像,这将有效。

var info = document.getElementById('info');
var svg = document.getElementById('svg');
var box = svg.getBoundingClientRect();

info.textContent = 'the ratio is ' + (box.width / box.height) + ' instead of 2.5! The yellow square is not in the viewBox, so why does it show up?';
.container {
  position: absolute;
  top: 40px;
  left: 40px;
  right: 40px;
  bottom: 40px;
}

.svg {
  position: absolute;
  max-height: 100%;
  max-width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: gray;
}
<div class="container">
<svg id="svg" class="svg" width="1000px" height="500px" viewBox="0 0 10 5">
   <rect width="10" height="5" fill="black" />
   <rect x="-2" y="2" width="1" height="1" fill="yellow" />
</svg>
</div>
<div id="info"/>

【问题讨论】:

  • 相信你也想达到和background-size: cover一样的效果。如果您不打算支持旧浏览器而只支持常绿浏览器,可以尝试object-fit: cover
  • @Terry:不,我正在尝试进行对象匹配:包含。不知道这些东西应该如何工作。一旦我删除最大宽度或最大高度,svg 就会变得太大
  • @CBroe:不确定这有什么帮助,溢出没有任何作用,我认为这不是我遇到的问题。
  • 那我想我不明白你到底遇到了什么问题......只有当你的 SVG 图像中有实际内容时,这些灰色部分才能被覆盖。如果容器不够高以显示整个图像...或 什么

标签: javascript css svg css-position


【解决方案1】:

从某种意义上说,您的 svg 已经按照您希望的方式安装在其容器中。事实上,您定义的大部分 CSS 都可以省略。 SVG 元素应使用width: 100%, height: 100% 定义,因此&lt;svg&gt; 元素本身具有与其容器相同的大小。然后将viewBox定义的区域根据preserveAspectRatio="xMidYMid meet"属性渲染到这个viewport中。 (隐式使用,这是它的默认值):保留纵横比,适合内部的最大尺寸,位于中间。

黄色矩形的问题只是因为内容被裁剪在 viewport 的边缘,而不是 viewBox。因此,在 SVG 中定义但在 viewBox 之外定义的内容可能仍然可见。

(最初的想法是在 &lt;svg&gt; 元素上支持 clip 样式属性,但其概念过于复杂以至于无法使用,现在已弃用。)

现在最好的解决方案是用另一个&lt;svg&gt; 包裹&lt;svg&gt; 元素。内层获得宽度和高度的绝对值,外层获得与 viewBox 和 width: 100%, height: 100% 相同的值。

如您所见,内层 svg 在其边缘剪辑内容,而外层将内容放入容器中。

请注意,您不能在内部 svg 上定义 CSS background-color。这仅针对 HTML 定义并且仅在外部元素上起作用,因为它是 HTML 元素的直接子元素。如果您想要彩色背景,请使用适当的fill 定义一个覆盖 viewBox 区域的矩形。

.container {
  position: absolute;
  top: 40px;
  left: 40px;
  right: 40px;
  bottom: 40px;
}

#svg1 {
  height: 100%;
  width: 100%;
  background-color: gray; /* clipped at the borders of the container! */
}
<div class="container">
  <svg id="svg1" class="svg" viewBox="0 0 10 5">
    <svg id="svg2" width="10" height="5">
      <rect width="10" height="5" fill="black" /> <!--this is your background-->
      <rect x="-2" y="2" width="1" height="1" fill="yellow" />
      <ellipse cx="5" cy="2.5" rx="6" ry="3"
               fill="none" stroke="blue" stroke-width="0.2" />
    </svg>
  </svg>
</div>
<div id="info"/>

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 2016-03-10
    • 2021-12-28
    • 2023-03-16
    • 2021-12-19
    • 2016-05-17
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    相关资源
    最近更新 更多