1.1 行内元素
.parent {
text-align: center;
}
1.2 块级元素
1.2.1 块级元素一般居中方法
.son {
margin: 0 auto;
}
1.2.2 子元素含 float
.parent{
width:fit-content;
margin:0 auto;
}
float: left;
}
1.2.3 Flex 弹性盒子
1) flex 2012版
.son {
display: flex;
justify-content: center;
}
2)flex 2009版
.parent {
display: box;
box-orient: horizontal;
box-pack: center;
}
1.2.4 绝对定位
1)transform
.son {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
2)left: 50%
.son {
postion: absolute;
width: 宽度;
left: 50%;
margin-left: -0.5*宽度
}
3)left/right: 0
.son {
position: absolute;
width: 宽度;
left: 0;
right: 0;
margin: 0 auto;
}
小结
以上是 CSS 水平居中的 8 种方法。
二、垂直居中
2.1 行内元素
.parent {
height: 高度;
}
line-height: 高度;
}
注:① 子元素 line-height 值为父元素 height 值。② 单行文本。
2.2 块级元素
2.2.1 行内块级元素
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
习惯 IE7。
2.2.2 table
.parent {
display: table;
}
.son {
display: table-cell;
vertical-align: middle;
}
利益
1)flex 2012版
.parent {
display: flex;
align-items: center;
}
利益
可用于更杂乱高级的布局技术中。
需求浏览器厂商前缀。
烘托上或许会有一些问题。
.parent {
display: box;
box-orien: vertical;
box-pack: center;
}
利益
1)transform
.son {
position: absolute;
top: 50%;
transform: translate( 0, -50%);
}
利益
.son {
position: absolute;
top: 50%;
height: 高度;
margin-top: -0.5高度;
}
利益
.son {
position: absolute;
top: 0;
botton: 0;
margin: auto 0;
}