将位置绝对div与中间对齐?

时间:2017-04-18 18:27:34

标签: html css

我有一个父div和一个子div。子div具有position: absolute属性。它已经居中,但我想将它与父div的中间对齐。我该怎么做呢?这是我的jsFiddle

HTML

<div id='parent'>
  <div id='child'>

  </div>
</div>

CSS

#parent {
  position: relative;
  width: 500px;
  height: 300px;
  background-color: red;
}

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 0;
  right: 0;
  margin: 0 auto;
  border-radius: 50%;
}

3 个答案:

答案 0 :(得分:6)

解决方案是在子div上使用transform: translate(-50%, -50%),如下所示:

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 50%;
  top: 50%;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

https://jsfiddle.net/jwoy7rxr/

这是有效的,因为变换会根据项目的原点来定位项目。

答案 1 :(得分:0)

由于父级具有基于px的高度,因此您可以安全地使用顶部和底部的简单边距来使元素居中。

#parent {
  position: relative;
  width: 500px;
  height: 300px;
  background-color: red;
}

#child {
  position: absolute;
  width: 70px;
  height: 70px;
  background-color: blue;
  left: 0;
  right: 0;
  margin: 115px auto;
  border-radius: 50%;
}

这是小提琴:https://jsfiddle.net/Lr3fLser/

答案 2 :(得分:0)

你需要给父母:

 #parent {
   width: 500px;
   height: 500px;
   background-color: red;
   display: table-cell;
   vertical-align: middle;
 }

 #child {
   width: 70px;
   height: 70px;
   background-color: blue;
   border-radius: 50%;
 }

您需要display table-cell才能使用vertical-align。

然后将align="center"添加到父div:

  <div align="center" id="parent">
    <div id='child'>

    </div>
 </div>

我附上了更新的JSFiddle:

https://jsfiddle.net/o7pzvtj3/2/

相关问题