##《 在这我为大家总结了下在一个div使其子div居中的方式4种方式,希望可以帮助的大家,》有喜欢的小伙伴,和喜欢交流分享的小伙伴欢迎加我微信:15633050186 小姐姐有惊喜的哦!!!
1.弹性布局
html代码:
<div class="father">
<div class="son"></div>
</div>
CSS样式:
.father{
width:400px;
height:400px;
background:black;
display: flex;
justify-content: center;
align-items:center;
}
.son{
width:200px;
height:200px;
background:red;
}
附图:
2.相对定位
html代码:
<div class="father">
<div class="son"></div>
</div>
CSS样式:
.father{
width:400px;
height:400px;
background:black;
position: absolute;
}
.son{
position: relative;
top: 100px;
left: 100px;
width:200px;
height:200px;
background:red;
附图:
3.相对定位的另一种方式
html代码:
<div class="father">
<div class="son"></div>
</div>
CSS样式:
.father{
width:400px;
height:400px;
background:black;
position: absolute;
}
.son{
position: relative;
top: 50%;
left: 50%;
margin-top:-100px; /*子元素宽高的一半 son/2*/
margin-left: -100px; /*子元素宽高的一半 son/2*/
width:200px;
height:200px;
background:red;
}
附图:
此方法较上一方法容易理解:
html代码:
<div class="father">
<div class="son"></div>
</div>
CSS样式:
.father{
width:400px;
height:400px;
background:black;
position: absolute;
}
.son{
position: relative;
margin-top:100px;
margin-left:100px;
width:200px;
height:200px;
background:red;
}
附图:
4.CSS位移
html代码:
<div class="father">
<div class="son"></div>
</div>
CSS样式:
.father{
width:400px;
height:400px;
background:black;
position: absolute;
}
.son{
position: relative;
transform: translate(50%,50%);
width:200px;
height:200px;
background:red;
}
附图:
喜欢的小伙伴点个赞?吧!!!,欢迎各位大佬的指教!!!! 微信:15633050186