编号 | 方法 | 居中类型 | 适用范围 |
1 | margin:10px auto (margin-left和margin-right设为auto) | 水平居中 | 只能进行水平的居中,且对浮动元素或绝对定位元素无效。 |
2 | inline-block配合text-align | 水平居中 | 优点:兼容性非常好,只需要添加只需要在子元素的css中添加*display:inline和*zoom:1就可兼容到IE6、7; 缺点:内部文字也会水平居中,需消除影响。 |
3 | table配合margin | 水平居中 | 设置特别简单,只需对子元素进行设置,支持IE8+,需支持IE6,7时,可更换子元素为表格结构 |
4 | abasolute配合transform | 水平居中 | 居中元素不对其他元素产生影响。 缺点:CSS3新属性支持IE9+,低版本浏览器不支持。 |
5 | table-cell配合vertical-align | 垂直居中 | 设置简单,只需对父元素进行设置,兼容到IE8+,需兼容地版本浏览器时,可更换div为表格结构。 |
6 | absolute配合tranform | 垂直居中 | 居中元素不对其他元素产生影响。 缺点:CSS3新属性支持IE9+,低版本浏览器不支持。 |
7 | inline-block配合text-align加上table-cell配合vertical-align | 水平+垂直居中 | 综合前两中方法,兼容性好!支持IE8+,低版本浏览器也好兼容。 缺点:设置较为复杂。 |
8 | absolute配合transform | 水平+垂直居中 | 优点:居中元素不对其他元素产生影响。 缺点:CSS3新属性支持IE9+,低版本浏览器不支持。 |
9 | flex | 水平居中 | |
10 | flex | 垂直居中 | |
11 | flex | 水平+垂直居中 | |
12 | text-align:center; | 水平居中 | 适用于行内元素 |
示例:
<div class="parent">
<div class="child">居中</div>
</div>
水平居中
编号1:
css
.parent {
margin: 32px auto;
background-color: aqua;
}
效果:
被居中的是class为parent的div
编号2
css
.parent{
text-align: center;
background-color: aliceblue;
}
.child{
display: inline-block;
background-color: aqua;
}
效果
被居中的是 class为child的div
编号3:
css
.child {
margin: 0 auto;
display:table;
background-color: aqua;
}
效果:
编号4:
css
.parent{
position:relative;
background-color: aqua;
}
.child{
position:absolute;
left:50%;
transform: translateX(-50%);
background-color: aliceblue;
}
效果:
垂直居中
编号5:
css:
.parent{
display: table-cell;
vertical-align:middle;
height: 200px;
background-color: aliceblue;
}
.child{
background-color: aquamarine;
}
效果:
编号6:
css:
.parent {
position: relative;
background-color: aliceblue;
height: 200px;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: aquamarine;
}
效果:
水平+垂直居中
编号7:
css:
.parent {
display: table-cell;
vertical-align: middle;
text-align: center;
background-color: aliceblue;
height: 200px;
width: 200px;;
}
.child {
display: inline-block;
background-color: aquamarine;
}
效果:
编号8:
css:
.parent {
position: relative;
background-color: aliceblue;
height: 200px;
width: 200px;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: aquamarine;
}
效果:同编号7
flex
编号9:
css
.parent {
display: flex;
justify-content: center;
}
或者:
.parent {
display: flex;
/* justify-content: center; */
}
.child {
margin: 0 auto;
}
效果:
编号10
css
.parent {
display: flex;
align-items: center;
background-color: aliceblue;
height: 200px;
width: 200px;
}
效果
编号11:
css
.parent {
display: flex;
justify-content: center;
align-items: center;
background-color: aliceblue;
height: 200px;
width: 200px;
}
或者:
.parent {
display: flex;
/* justify-content: center; */
align-items: center;
background-color: aliceblue;
height: 200px;
width: 200px;
}
.child {
margin: auto;
}
效果:
注意:css中背景颜色和宽高属性与居中无关系,仅为了好看效果
注意:我们要居中的是class为child的div!