【问题标题】:How can I horizontally center an svg grouped circle (two paths)?如何水平居中 svg 分组圆(两条路径)?
【发布时间】:2019-01-20 02:16:18
【问题描述】:

我有一个显示 svg 圆圈的 html 文档。它不是一个真正的 svg 圆,但它是由两条路径构建的。见下文。 另见https://codepen.io/anon/pen/xmomBg

问题: 我想在浏览器 winodw 中居中这个对象。 StackFlow 提供了一些解决方案,使用 style="margin: 0 auto;" 的变体。但是,似乎只适用于某些(更简单的?) svg 图像。我使用的 svg 导致仅将圆的左侧部分居中,而不是整个圆。 codepen 直观地显示了我的问题。

HTML

<div class="c-container" style="margin: 0 auto;">
  <svg id="yeah" viewbox="0 0 100 100">
    <path id="bg" stroke-linecap="round" stroke-width="4" stroke="#212b37" fill="none" d="M50 2 
       a 48 48 0 0 1 0 96 
       a 48 48 0 0 1 0 -96">
    </path>
    <path id="progress" stroke-linecap="round" stroke-width="4" stroke="#7bdccd" fill="none" d="M50 2 
       a 48 48 0 0 1 0 96 
       a 48 48 0 0 1 0 -96">
    </path>
  </svg>
</div>

CSS

body{
  background: #1c222e;
  padding: 30px;
}
.c-container {
  width: 100px;
  svg {
    width: 500%;
  }
}

【问题讨论】:

  • 删除 100px 并将其替换为 500px 然后删除 500% ...(100px 的 500% 将是 500px)
  • 改用这个 css:body{ background: #1c222e; padding: 30px; } .c-container { width: 500px; svg { /*width: 500%;*/ } } SVG 将占用所有可用的宽度

标签: html css svg


【解决方案1】:

问题在于您的 svg 上的 width: 500%

你的容器应该有一个 widthmargin-leftmargin-right auto。这将确保它居中。

鉴于 SVG 没有自己的 widthheight,它将扩展到其父容器的 100%。

所以让容器进行缩放,允许 SVG 被其容器缩放。

body {
  background: #1c222e;
  padding: 30px;
}

.c-container {
  margin: 0 auto;
}

.c-container-500 {
  max-width: 500px;
}

.c-container-100 {
  max-width: 100px;
}
<div class="c-container c-container-500">
  <svg id="yeah" viewbox="0 0 100 100">
        <path id="bg" stroke-linecap="round" stroke-width="4" stroke="#212b37" fill="none" d="M50 2 
           a 48 48 0 0 1 0 96 
           a 48 48 0 0 1 0 -96">
        </path>
        <path id="progress" stroke-linecap="round" stroke-width="4" stroke="#7bdccd" fill="none" d="M50 2 
           a 48 48 0 0 1 0 96 
           a 48 48 0 0 1 0 -96">
        </path>
    </svg>
</div>

<div class="c-container c-container-100">
  <svg id="yeah" viewbox="0 0 100 100">
        <path id="bg" stroke-linecap="round" stroke-width="4" stroke="#212b37" fill="none" d="M50 2 
           a 48 48 0 0 1 0 96 
           a 48 48 0 0 1 0 -96">
        </path>
        <path id="progress" stroke-linecap="round" stroke-width="4" stroke="#7bdccd" fill="none" d="M50 2 
           a 48 48 0 0 1 0 96 
           a 48 48 0 0 1 0 -96">
        </path>
    </svg>
</div>

Codepen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    • 2021-11-18
    • 2012-10-24
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多