html - 在容器中居中响应式 svg 圆圈

标签 html css svg

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 translateg 元素上使用百分比似乎有问题,这使我无法执行 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>

您始终需要使用 cxcy 确定圆心,如果没有说明,这将默认为 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/

相关文章:

javascript - 单击时动态地为每个 id 获取 jquery getjson - ruby​​ on rails

html - Firefox 没有遵守 rel=stylesheet 链接的 'disabled' 属性

css - 如何使用对象标签为 SVG 设置动画

html - 在 Bootstrap 4 中创建导航栏和子导航栏

javascript - 移除 HTML 标签并保留文本

html - 如何在低于 767px 宽度时从 DIV 中删除左边距

javascript - Slidedown div 未出现在表单提交中

html - CSS 图像裁剪然后调整大小

javascript - SVG 用类声明替换填充声明,用于高级颜色自定义

svg - 有没有办法在 C# 中清理 SVG 文件,有什么库吗?