如何使用CSS中的绝对位置将孩子div定位到每个父母div的中心 [英] How to position child div to the center of every parents div using position absolute in css
本文介绍了如何使用CSS中的绝对位置将孩子div定位到每个父母div的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难在每个父母div上定位子div.
I'm having difficulty on positioning child div's on every parents 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%;
}
这是小提琴
推荐答案
对此子级div进行转换,它将起作用!
Use transform for that to the child div and it will work!
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>
这篇关于如何使用CSS中的绝对位置将孩子div定位到每个父母div的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文