2017-05-25 80 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的解決方案在那裏,但瀏覽器的支持可能不是你所需要它的人。