CSS中DIV水平垂直居中方法
时间:2023-3-4 09:48 作者:小诸葛 分类: 前端 正在检查是否收录...
效果图
第一种
HTML
<div class="box1">
<div class="box2">
</div>
</div>
CSS
.box1{
width: 100px;
height: 100px;
background-color: #ff5500;
/* 相对定位 */
position:relative;
}
.box2{
width: 50px;
height: 50px;
background-color: #ffaaff;
/* 绝对定位 */
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
}
第二种
CSS
.box1{
width: 100px;
height: 100px;
background-color: #ff5500;
/* 相对定位 */
position:relative;
}
.box2{
width: 50px;
height: 50px;
background-color: #ffaaff;
/* 绝对定位 */
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: auto;
}
第三种
CSS
.box1{
width: 100px;
height: 100px;
background-color: #ff5500;
/* 相对定位 */
position:relative;
margin: 0 auto;
}
.box2{
width: 50px;
height: 50px;
background-color: #ffaaff;
/* 绝对定位 */
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%);
}
第四种
css
.box1{
width: 100px;
height: 100px;
background-color: #ff5500;
display: flex;
justify-content: center;
align-items: center;
}
.box2{
width: 50px;
height: 50px;
background-color: #ffaaff;
}
推荐阅读:
扫描二维码,在手机上阅读