实现方式
-
定位 + margin:auto
-
定位 + margin: 负值
-
定位 + transform
-
table布局
-
flex布局
-
grid网格布局
定位+margin:auto
<style>
.father{
width:500px;
height:300px;
border:1px solid #0a3b98;
position: relative;
}
.son{
width:100px;
height:40px;
background: #f0a238;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
</style>
<div class="father">
<div class="son"></div>
</div>
父级元素开启相对定位,子级元素开启绝对定位,并且四个定位属性全部设置为0,这时候看似子元素的宽高设置了那么多,但是实际上子元素的占位已经填满了父级元素,这时候设置margin:auto,子元素就会默认水平垂直居中于父级元素
定位+margin:负值
绝大多数情况下,设置父元素为相对定位, 子元素移动自身50%实现水平垂直居中
<style>
.father {
position: relative;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
position: absolute;
top: 50%;
left: 50%;
margin-left:-50px;
margin-top:-50px;
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
定位+transform
这个方法和上面的差不多,而且更好用,不需要去考虑子元素自身的宽高
<style>
.father {
position: relative;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
table布局
设置父级元素 display:table-ceil,子级元素设置 display: inline-block ,利用属性,vertical,text-align,就可以实现子级元素水平垂直居中
<style>
.father {
display: table-cell;
width: 200px;
height: 200px;
background: skyblue;
vertical-align: middle;
text-align: center;
}
.son {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
flex布局
这应该是我认为的最简单也是最好用的方法了吧,只需要设置父级盒子为弹性盒子,再设置两条交叉轴上居中即可,当然这只是flex布局的一种好处,flex远不止这点
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
grid网格布局
在垂直居中的问题上网格布局和flex布局一样,简单粗暴就能实现
<style>
.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 10px;
height: 10px;
border: 1px solid red
}
</style>
<div class="father">
<div class="son"></div>
</div>
总结,内联文本水平垂直居中,可多用 line-height + text-algin , 行内块元素可以用table布局,但是不太建议,也可采用内联文本的那种形式,或者使用flex布局,正常的使用grid和flex布局即可,简单方便