2016-12-07 106 views
0

我創建了一個SVG並將寬度設置爲百分比,因爲我希望它調整大小以適應不同的屏幕寬度,但是當我調整屏幕大小時, svg上下移動,不會左右移動以保持中心位置。如果我使用像素而不是百分比,則不會隨屏幕調整大小。當屏幕尺寸發生變化或無法縮放時,SVG移出位置

預覽沒有在這裏工作,所以here's the codepen link

HTML

<svg height="100%" width="100%" id="main"> 
    <circle class="graph line line-1" cx="50%" cy="50%" r="25%" stroke-width="5%" stroke="#f1c40f" fill="none" /> 
    <circle class="graph line line-2" cx="50%" cy="50%" r="20%" stroke-width="5%" stroke="#e67e22" fill="none" /> 
    <circle class="graph line line-3" cx="50%" cy="50%" r="15%" stroke-width="5%" stroke="#00c0df" fill="none" /> 
</svg> 

CSS

#main { 
    padding: 100px 0; 
    margin-top: 100px; 
    height: 200px; 
    background-color: pink; 
} 

.graph { 
    transform: rotate(270deg); 
} 

.graph.line { 
    transform-origin: center; 
    stroke-dasharray: 160%; 
    animation: graph 1.5s ease-in-out infinite alternate; 
} 
@keyframes graph { 
    from { 
    stroke-dashoffset: 160%; 
    } 
    to { 
    stroke-dashoffset: 90%; 
    } 
} 

回答

1

這就是視框的。使用viewBox,您可以建立一個局部座標系,並與您的圖像一起縮放。在你的SVG您只需使用你的本地座標和圖像擴展到任何規模大小...

#main { 
 
    position:absolute; 
 
    top:0px;left:0px; 
 
    right:0px;bottom:0px; 
 
    background:pink 
 
} 
 

 
.graph { 
 
    transform: rotate(270deg); 
 
} 
 

 
.graph.line { 
 
    transform-origin: center; 
 
    stroke-dasharray: 160%; 
 
    animation: graph 1.5s ease-in-out infinite alternate; 
 
} 
 
@keyframes graph { 
 
    from { 
 
    stroke-dashoffset: 160%; 
 
    } 
 
    to { 
 
    stroke-dashoffset: 90%; 
 
    } 
 
}
<svg viewBox="0 0 100 100" id="main"> 
 
    <circle class="graph line line-1" cx="50" cy="50" r="25" stroke-width="5" stroke="#f1c40f" fill="none" /> 
 
    <circle class="graph line line-2" cx="50" cy="50" r="20" stroke-width="5" stroke="#e67e22" fill="none" /> 
 
    <circle class="graph line line-3" cx="50" cy="50" r="15" stroke-width="5" stroke="#00c0df" fill="none" /> 
 
</svg>

+0

甜!我如何改變svg的大小?如果我在其上放置一定寬度,那麼如果我縮小移動屏幕或視圖,它會伸出頁面外部。 – Sean

+0

你可以使用任何方式的CSS來改變svg的大小。 –