2016-12-07 105 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的大小。 –