如何在div的中间对齐svg圈?

问题描述 投票:1回答:2

我需要创建一个圆圈来模拟在Mac OS中关闭窗口的按钮。但当我试图将它降低时,svg的边界会将其切断。如何移动边框以将圆圈直接放置在面板中间(垂直)?

的jsfiddle:https://jsfiddle.net/sm6r0kvn/2/

<div class="panel">
  <svg viewbox="0 0 20 17" width="20" heigth="50"><circle r="7" cx="14" cy="9.5" fill="#fc615e"/></svg>
</div>
html css css3 svg centering
2个回答
3
投票

您可以像<svg viewbox="0 0 20 20" width="20" heigth="20">一样设置视图框,然后将cxcy设置为50%。如果你想将它放在panel垂直中心,只需将它设为flexbox并添加align-items: center - 请参阅下面的演示:

.block {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  max-width: 550px;
  min-width: 480px;
  width: 80vw;
  height: 200px;
  background: black;
  border-radius: 10px 10px 5px 5px;
}

.panel {
  background-color: #e0e0e0;
  border-radius: 5px 5px 0 0;
  display: flex; /* added */
  align-items: center; /* added */
}

.text {
  color: white;
  padding: 5px;
}
<div class="block">
  <div class="panel">
    <svg viewbox="0 0 20 20" width="20" heigth="20">
      <circle r="7" cx="50%" cy="50%" fill="#fc615e"/>
    </svg>
  </div>
  <div class="text">
    Text here
  </div>
</div>

1
投票

这是因为您正在svg视图框之外绘制圆圈。您可以使用CSS移动整个svg框或使其更大

svg {
  border: 1px blue solid;
}
.panel.moved {
  margin-left: 100px;
}
<div class="panel">
  <svg viewbox="0 0 20 20" width="200" heigth="200">
    <circle r="10" cx="10" cy="10" fill="#fc615e"/>
  </svg>
</div>
<div class="panel">
  <svg viewbox="0 0 20 20" width="200" heigth="200">
    <circle r="10" cx="20" cy="10" fill="#fc615e"/>
  </svg>
</div>
<div class="panel">
  <svg viewbox="0 0 30 20" width="300" heigth="200">
    <circle r="10" cx="20" cy="10" fill="#fc615e"/>
  </svg>
</div>
<div class="panel moved">
  <svg viewbox="0 0 20 20" width="200" heigth="200">
    <circle r="10" cx="10" cy="10" fill="#fc615e"/>
  </svg>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.