Demo
html
<div class="father">
<ul class="center">
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
</div>
css
.father {
background-color: green;
}
.center {
background-color: orange;
}
效果:
实现
1.宽度已知,使用margin
.center {
background-color: orange;
width: 100px;
margin: 0 auto;
}
效果:
适用:
只能进行水平居中,对浮动元素或绝对定位元素无效
2.宽度已知,使用绝对定位
.father {
background-color: green;
text-align: center;
position: relative;
}
.center {
background-color: orange;
position: absolute;
width: 200px;
left: 50%;
margin-left: -100px;
}
效果
原理:
把这个绝对定位的元素的left或top设置为50%,这时候并不是居中的,而是把这个元素向右移动父元素一半的距离,再使用一个负的margin-left或者margin-top的值把它拉回到居中位置,这个值取该元素宽度或高度的一半。
优点:
兼容IE6-7
缺点:
不能使用百分比大小,内容高度不可变;内容可能会超过容器;
3.宽度已知,使用绝对定位来实现完全居中
.father {
background-color: green;
position: relative;
width: 300px;
height: 300px;
}
.center {
background-color: orange;
position: absolute;
width: 200px;
height: 200px;
margin: auto;
/*这句必不可少*/
left: 0;
/*left与right必须成对出现来控制水平方向*/
right: 0;
bottom: 0;
/*top与bottom必须成对出现来控制水平方向*/
top: 0;
}
效果
4.宽度已知,使用绝对定位+transform
.father {
background-color: green;
position: relative;
width: 400px;
height: 400px;
}
.center {
background-color: orange;
list-style-type: none;
padding: 0;
position: absolute;
width: 50%;
height: 50%;
margin: auto;
top: 50%;
left: 50%;
/* 元素从当前位置,向左向下移动 */
transform: translate(-50%, -50%);
}
效果:
优点:
内容高度可变,可以使用百分比
缺点:
不兼容IE8;会与其他transform样式冲突。
5.宽度不定,使用text-align:center+display:inline-block
.father {
background-color: green;
text-align: center;
}
.center {
background-color: orange;
display: inline-block;
}
效果
适用:
只能对图片、按钮、文字等行内元素(display为inline或inline-block等)进行水平居中。在IE6、7这两个浏览器中,它是能对任何元素进行水平居中的。
6.宽度不定,使用弹性盒子的justify-content属性
.father {
background-color: green;
text-align: center;
display: flex;
justify-content: center;
}
.center {
background-color: orange;
}
效果
7.使用display:table-cell
.father {
background-color: green;
display: table-cell;
width: 400px;
height: 400px;
vertical-align: middle;
}
.center {
background-color: orange;
list-style-type: none;
width: 50%;
padding: 0;
margin: 0 auto;
}
效果:
原理:
对于那些不是表格的元素,我们可以通过display:table-cell 来把它模拟成一个表格单元格,这样就可以利用表格那很方便的居中特性了。
优点:浏览器兼容性好