一、单行文本水平垂直居中
1.文本水平居中:给文本的父盒子设置text-align: center;即可
2.文本垂直居中: 给文本设置line-height的值与父盒子height的值相等
<style>
.box {
width: 200px;
height: 200px;
background-color: palegreen;
text-align: center;
line-height: 200px;
}
</style>
<div class="box">
box
</div>
3.利用弹性盒模型,设置align-item:center;justify-content:center;实现文本水平垂直居中
<style>
.box {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background-color: palegreen;
}
</style>
<div class="box">
box
</div>
二、块级元素水平垂直居中
方法一:
父元素相对定位+子元素绝对定位+手动计算margin
<style>
.box {
position: absolute;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: palegreen;
}
</style>
<div class="box"></div>
方法二:
父元素相对定位+子元素绝对定位+transform
<style>
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: palegreen;
}
</style>
<div class="box"></div>
方法三:
父元素相对定位+子元素绝对定位+ top:0;right:0;bottom:0;left:0; +margin:auto
<style>
.box {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: palegreen;
}
</style>
<div class="box"></div>
方法四:
给父盒子设置display:flex;开启弹性布局,然后设置align-item:center;justify-content:center;
<style>
body {
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 200px;
height: 200px;
background-color: palegreen;
}
</style>
<div class="box"></div>