对齐位置绝对div到中间



我有父母div和一个孩子div。Child Div具有position: absolute属性。它已经以中心为中心,但是我想将其对齐到父级的中间。我该怎么做?这是我的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%;
}

解决方案是在儿童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/

这起作用是因为转换基于其自身原产地的百分比定位项目。

由于父母基于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/

您需要给父母:

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

您需要显示台式电池才能使用垂直空缺。

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

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

我已随附更新的JSFIDDLE:

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

最新更新