How to position child div to the center of every parents div using position absolute in css [duplicate]

偶尔善良 提交于 2019-11-29 16:50:55

Use transform for that to the child div and it will work!

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

snippet below:

.mainDiv {
  height:500px;
  
  position: relative;
}

.mainDiv .parent1 {
  height: 250px;
  background-color: blue;
   position: relative;
}

.mainDiv .parent2 {
  height: 250px;
  background-color: yellow;
   position: relative;
}


.mainDiv .parent1 .sub1 {
  width: 100px;
  height: 100px;
  background-color: green;

  position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    
}

.mainDiv .parent2 .sub2 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
<div class="mainDiv">
  <div class="parent1">
    <div class="sub1">
        
    </div>
  </div>
  <div class="parent2">
    <div class="sub2">
      
    </div>
  </div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!