如何使用css中的绝对位置将子div定位到每个父div的中心

时间:2016-08-11 09:45:21

标签: html css css-position vertical-alignment centering

我很难在每个父母的div上定位孩子。

这是css代码:

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

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

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


.mainDiv .parent1 .sub1 {
  width: 100px;
  height: 100px;
  background-color: green;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  top: 50%;
}

.mainDiv .parent2 .sub2 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  top: 50%;
}

这里是fiddle

1 个答案:

答案 0 :(得分:5)

对子div使用transform,它会起作用!

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

以下片段:

.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>