水平、垂直居中的方法 (已知宽高/未知宽高)
--------------一、居中元素 已知宽高----------------------
1、margin — 根据已知的宽高写死,不推荐
.div1{
height:400px;
background-color: #f7f7f7;
padding-top: 150px;
padding-bottom: 150px;
box-sizing: border-box;
}
.div2{
width: 100px;
height: 100px;
background-color: deepskyblue;
margin: 0 auto;
}
2、定位 + margin-top + margin-left
.div1{
height:400px;
background-color: #f7f7f7;
position: relative;
}
.div2{
width: 150px;
height: 100px;
background-color: deepskyblue;
position: absolute;
left: 50%;
top: 50%;
margin-left: -75px;
margin-top: -50px;
}
3、定位 + margin
.div1{
height:400px;
background-color: #f7f7f7;
position: relative;
}
.div2{
width: 150px;
height: 100px;
background-color: deepskyblue;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
4、定位 + transform --- 存在兼容问题
.div1{
height:400px;
background-color: #f2f2f2;
position: relative;
}
.div2{
width: 100px;
height: 100px;
background-color: #f00;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
5、flex 布局 --- 存在兼容问题
.div1{
height:400px;
display: flex;
justify-content: center;
align-items: center;
background-color: #f2f2f2;
}
.div2{
width: 100px;
height: 100px;
background-color: #749DCF;
}
--------------二、居中元素 未知宽高----------------------
1、定位 + transform — 存在兼容问题
设置父元素为相对定位,子元素绝对定位
.div3{
height:400px;
background-color: #f2f2f2;
position: relative;
}
.div4{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2、flex 布局 --- 存在兼容问题
设置父元素为 flex 弹性盒模型,并在主轴和副轴上设置居中
.div3{
height:400px;
display: flex;
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
justify-content: center;
align-items: center;
background-color: #f2f2f2;
}
3、display: table-cell --- 早期属性 无兼容问题
//父级要固定宽高
.div3{
width: 800px;
height: 400px;
background-color: #f2f2f2;
display: table-cell;
text-align: center;
vertical-align: middle;
}
HTML
<body>
<div class="div1">
<div class="div2">居中元素 已知宽高</div>
</div>
<div class="div3">
<div class="div4">居中元素 未知宽高</div>
</div>
</body>
总结起来是以下几点:
水平居中
行内元素: text-align: center
块级元素: margin: 0 auto
position:absolute +left:50%+ transform:translateX(-50%)
display:flex + justify-content: center
垂直居中
设置line-height 等于height
position:absolute +top:50%+ transform:translateY(-50%)
display:flex + align-items: center
display:table+display:table-cell + vertical-align: middle;
如有错误或不足,欢迎各位大佬评论指正。