将响应式svg圆在容器中居中 [英] Centering responsive svg circle in container

查看:83
本文介绍了将响应式svg圆在容器中居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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; }
}

正如您在测试页中所看到的,我试图将一个响应圆放置在一定的半径上,并且我希望它可以将其自身放置在容器的中间,而不管容器的宽度如何.如果圆也适合容器的高度,那就更好了.

As you can see in the test page, I am trying to position a responsive circle with some radius, and I want it to position itself in the middle of the container, regardless the width of the container. It would be even better if the circle also fit itself to the height of the container.

g元素上使用百分比的css translate似乎存在问题,这使我无法执行translate(-50%, -50%)

There seem to be a problem with css translate using percentages on the g element, which prevents me from just doing translate(-50%, -50%)

这是我所拥有的东西的非常简化的版本,因为在我的代码中它是一个甜甜圈图,这就是为什么它对此进行了rotate转换

推荐答案

如果希望SVG为圆的大小,则需要将视图框设置为半径的两倍并确定中心点.

If you want the SVG to be the size of the circle you need to set the viewbox to twice the radius and determine a center point.

圆以cx,cy为中心,半径为r. cx,cy和r是元素的属性.

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(左上).

You always need to determine the center of the circle using cx and cy which will default to 0,0 (left top) if not stated.

或者,对于独立于视图框的中心圆,您可以使用%半径.

Alternatively, for a viewbox-independent centered circle you could use a % radius.

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>

看到区别了吗?

参考 链接 与教程&视频

Reference Link with tutorials & video

这篇关于将响应式svg圆在容器中居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆