Test page
标记:
<svg viewBox="0 0 400 400" preserveAspectRatio="xMinYMin meet">
<g>
<circle r="70" class="circle-back" />
</g>
</svg>
CSS
.doughnutChart{
text-align:center;
padding:50% 1em 0;
position: relative;
overflow: hidden;
> svg{
position: absolute;
top: 0;
left:0; right:0;
margin: auto;
g{ transform:rotate(270deg) translate(-88px, 200px); }
}
circle{ fill: none; }
.circle-back { stroke:#EEE; stroke-width: 5px; }
}
如您在测试页面中所见,我试图放置一个具有一定半径的响应圆,并且我希望它能够将自身定位在容器的中间,而不管容器的宽度如何。如果圆圈也适合容器的高度,那就更好了。
css translate
在 g
元素上使用百分比似乎有问题,这使我无法执行 translate(-50%, -50 %)
这是我所拥有的一个非常简化的版本,因为在我的代码中它是一个圆环图,这就是为什么它有这个 rotate
转换到它
最佳答案
如果您希望 SVG 为圆的大小,您需要将视框设置为半径的两倍并确定一个中心点。
The circle is centered in cx , cy and has a radius of r. cx, cy and r are attributes of the element.
svg {
height: 100px;
border: 1px solid green;
}
circle {
fill: none;
}
.circle-back {
stroke: #EEE;
stroke-width: 5px;
}
<svg viewBox="0 0 140 140" preserveAspectRatio="xMinYMin meet">
<g>
<circle r="70" cx="50%" cy="50%" class="circle-back" />
</g>
</svg>
您始终需要使用 cx
和 cy
确定圆心,如果没有说明,这将默认为 0,0(左上)。
或者,对于独立于 View 框的中心圆,您可以使用 % 半径。
svg {
height: 100px;
border: 1px solid plum;
}
circle {
fill: none;
}
.circle-back {
stroke: #EEE;
stroke-width: 5px;
}
<svg viewBox="0 0 140 140" preserveAspectRatio="xMinYMin meet">
<g>
<circle r="50%" cx="50%" cy="50%" class="circle-back" />
</g>
</svg>
在您的原始代码中。
svg {
height: 100px;
border: 1px solid red;
}
circle {
fill: none;
}
.circle-back {
stroke: #EEE;
stroke-width: 5px;
}
<svg viewBox="0 0 400 400" preserveAspectRatio="xMinYMin meet">
<g>
<circle r="70" cx="200" cy="200" class="circle-back" />
</g>
</svg>
看出区别了吗?
引用 Link有教程和视频
关于html - 在容器中居中响应式 svg 圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33135429/