2017-05-25 81 views
0

为什么在SVG元素上设置viewbox属性会弄乱高度并导致溢出?我怎样才能防止呢?SVG ViewBox Breaks高度

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

+0

如果你想防止溢出显示你可以添加'overflow-y:hidden'到**。parent ** div。 – Arthur

+0

我宁愿如果svg不占用太多空间,而是缩放其内容。 – Henning

+0

这也会发生在图像上,它并不是SVG和viewBox属性的使用。 – hungerstar

回答

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的解决方案在那里,但浏览器的支持可能不是你所需要它的人。