代码之家  ›  专栏  ›  技术社区  ›  edeboursetty

在容器中居中放置大型svg

  •  -1
  • edeboursetty  · 技术社区  · 9 年前

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

    由于某些原因,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"/>
    1 回复  |  直到 9 年前
        1
  •  1
  •   ccprog    9 年前

    width: 100%, height: 100% ,所以 <svg> viewBox 视口 根据属性 preserveAspectRatio="xMidYMid meet"

    黄色矩形出现问题的唯一原因是内容被剪裁在 视口 ,而不是 视图框 . 因此,在SVG中定义但在viewBox之外的内容可能仍然可见。

    clip 上的样式属性 <svg> 元素,但它的概念非常复杂,无法使用,现在已被弃用。)

    现在最好的解决方案是将 <svg> 元素与另一个元素 < 宽度:100%,高度:100% .

    请注意,您不能定义CSS background-color fill .

    .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"/>