本文总结了布局中实现元素水平居中、垂直居中及水平垂直居中的常用方法
一、水平居中
1)文本 / 行内元素 / 行内块级元素
#parent { text-align: center; }
2)单个块级元素
ele {
width: 100px; // 必须定宽
margin: 0 auto;
}
3)多个块级元素
#parent {
text-align: center;
}
.son {
display: inline-block;
}
4)子元素实现居中,使用绝对定位实现 (子绝父相)
#parent {
position: relative;
width: 200px;
}
#son {
position: absolute;
left: 50%; // 父元素宽度的一半
width: 100px;
transform: translateX(-50%); // 向左拉回子元素自身宽度的一半
}
5)任意个元素(flex)
#parent {
display: flex;
justify-content: center;
}
二、垂直居中
1)单行文本 / 行内元素 / 行内块级元素
#parent {
height: 150px;
line-height: 150px;
}
2)多行文本(文本用一个标签包裹起来)
#parent {
height: 200px;
line-height: 200px;
}
.son {
display: inline-block;
vertical-align: middle;
line-height: 20px;
}
3)图片
#parent {
height: 150px;
line-height: 150px;
font-size:0;
}
img {
vertical-align: middle;
}
4)单个块级元素
#parent {
position: relative;
height: 200px;
}
#son {
position: absolute;
top: 50%;
height: 100px;
transform: translateY(-50%);
}
或
原理: 当元素的 top、bottom为0时,该元素的 margin-top/bottom设置为auto的话会自动分配剩余空间
#son {
position: absolute;
top: 0;
bottom: 0;
height: 100px;
margin: auto 0;
}
5)任意个元素(flex)
#parent {
display: flex;
align-items: center;
}
三、水平垂直居中
1)text-align、line-height及vertical-align三者结合
#parent {
width: 500px;
height: 500px;
line-height: 500px;
text-align: center;
}
#son {
display: inline-block;
width: 200px;
height: 200px;
line-height: 20px;
vertical-align:middle;
}
2)table-cell
#parent {
display: table-cell;
width: 600px;
height: 400px;
vertical-align: middle;
text-align: center;
background-color: skyblue;
}
#son {
display: inline-block;
width: 200px;
height: 300px;
background-color: slateblue;
}
3)绝对定位
#parent {
position: relative;
}
#son {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
}
4)绝对居中
原理:当元素的 top、bottom、left、right同时为0时,该元素的 margin-top/bottom/left/right设置为 auto 的话会自动平分剩余空间
#parent {
position:relative;
}
#son {
position: absolute;
left:0;
right:0;
top:0;
bottom:0;
width:200px;
height:200px;
margin: auto;
}
5)flex
#parent {
display:flex;
justify-content:center;
align-items:center;
}