div垂直居中知几种?
文章目录
html结构:实现box在wrap中垂直居中
<div class="wrap">
<div class="box"></div>
</div>
方法一 flex弹性盒子实现
.wrap {
display: flex;
align-items: center;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.box {
width:100px;
height: 100px;
background: red;
}
方法二 relative和absolute实现
.wrap {
position: relative;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.box {
position: absolute;
top: 50%;
margin-top: -50px;
width:100px;
height: 100px;
background: red;
}
方法三
.wrap {
position: relative;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.box {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
width:100px;
height: 100px;
background: red;
}
方法四
.wrap {
position: relative;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.box {
position: absolute;
top: 50%;
transform: translateY(-50%);
width:100px;
height: 100px;
background: red;
}
方法2-4 都是相对定位和绝对定位配合实现, 但是方式略有不同
方法五 table-cell和vertical-align实现
.wrap {
display: table-cell;
vertical-align: middle;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.box {
width:100px;
height: 100px;
background: red;
}
由于上传图片老是报错,后面会把图片加上

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论