一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第12天,点击查看活动详情。
一。块元素的水平居中方式
1。 /* 使用弹性盒模型实现水平垂直居中 */ display: flex; justify-content: center; align-items: center;
<style>
.box {
width: 25rem;
height: 25rem;
border: 1px solid red;
/* 使用弹性盒模型实现水平垂直居中 */
display: flex;
justify-content: center;
align-items: center;
}
.a {
width: 6.25rem;
height:220px;
background: yellow;
}
</style>
<div class="box">
<div class="a"></div>
</div>
2.使用父元素相对定位,子元素绝对定位
①.
<style>
.box {
width: 25rem;
height: 25rem;
border: 1px solid red;
position: relative;
}
.a{
width:100px;
height:220px;
background: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-top: -110px;
/* 顶部边距是高的一半 */
margin-left: -50px;
/* 左边距是宽的一半 */
}
</style>
<div class="box">
<div class="a"></div>
</div>
②。
<style>
.box {
width: 25rem;
height: 25rem;
border: 1px solid red;
position: relative;
}
.a{
width:100px;
height:220px;
background: yellow;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50px,-110px);
}
</style>
<div class="box">
<div class="a"></div>
</div>
③。
<style>
.box {
width: 25rem;
height: 25rem;
border: 1px solid red;
position: relative;
}
.a{
width:100px;
height:220px;
background: yellow;
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
<div class="box">
<div class="a"></div>
</div>
二。行内元素垂直居中
1.单行垂直居中
<style>
.box {
width: 25rem;
line-height: 25rem;
border: 1px solid red;
text-align: center;
}
</style>
2.多行垂直
<style>
.box {
width: 25rem;
height: 25rem;
border: 1px solid red;
display: table;
}
span {
display: table-cell;
vertical-align: middle;
}
</style>