如何在直线上将圆垂直居中?

时间:2019-05-14 09:27:14

标签: html css

我试图在水平线的中间垂直居中放置一个圆,但是使用负边距似乎不起作用。我应该如何处理?

#line {
  width: 100%;
  /* 2 */
  height: 5px;
  background: gray;
}

#circle {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background: blue;
  margin-left: 50%;
  text-align: center;
  color: white;
  font-weight: 700;
  line-height: 50px;
  font-size: 14px;
}
<div id="Value">0.33</div>
<div id="Result"></div>


<div id="line">
  <div id="circle">
    2
  </div>
</div>

4 个答案:

答案 0 :(得分:1)

这应该有效:

margin-left: calc(50% - 25px);

您可以在此处了解有关CSS Calc的信息: https://developer.mozilla.org/en-US/docs/Web/CSS/calc

答案 1 :(得分:1)

使用绝对定位和transform

#line {
  width: 100%;
  height: 5px;
  background: gray;
  position: relative;
}

#circle {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background: blue;
  text-align: center;
  color: white;
  font-weight: 700;
  line-height: 50px;
  font-size: 14px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div id="Value">0.33</div>
<div id="Result"></div>


<div id="line">
  <div id="circle">
    2
  </div>
</div>

答案 2 :(得分:0)

请检查您是否在寻找这个?

#line {
  width: 100%;
  /* 2 */
  height: 5px;
  background: gray;
  position: relative;
}

#circle {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background: blue;
  margin-left: -25px;
  text-align: center;
  color: white;
  font-weight: 700;
  line-height: 50px;
  font-size: 14px;
  position: absolute;
  left: 50%;
  bottom: 0;
}
<div id="Value">0.33</div>
<div id="Result"></div>


<div id="line">
  <div id="circle">
    2
  </div>
</div>

如果您想将圆圈移到线的顶部,请调整bottom: 0;

答案 3 :(得分:0)

使用position:absolute并将margin-left:calc(50% - 25px)margin-top:-22.5px更改为线的垂直和水平中心(硬编码的宽度和高度圆)

#line {
  width: 100%;
  /* 2 */
  height: 5px;
  background: gray;
  position:relative;
}

#circle {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background: blue;
  margin-left: calc(50% - 25px);
  text-align: center;
  color: white;
  font-weight: 700;
  line-height: 50px;
  font-size: 14px;
  position:absolute;
  margin-top:-22.5px;
}
<div id="Value">0.33</div>
<div id="Result"></div>


<div id="line">
  <div id="circle">
    2
  </div>
</div>