(1) text-align方法:
在父元素中加入"text-align:center;",所有子元素自然水平居中。
也正是因为会使所有子元素水平居中,所以在只需要某个子元素水平居中的情况下并不适用。
.eg{
text-align:center;
}
(2) 浮动方法:
先让父元素左浮动50%,再让子元素右浮动50%,即可实现水平居中。
.father{
clear: left;
float: left;
position: relative;
left: 50%; /*向右边移动宽度的50%*/
text-align: center;
}
.sun{
float: left;
position: relative;
right: 50%; /*向左边移动宽度的50%*/
}
(3)绝对定位方法:
与浮动方法相似,不过绝对定位会影响布局,谨慎使用。
.father {
position: absolute;
left: 50%;
}
.sun {
float: left;
position: relative; /*注意,这里不能是absolute*/
right: 50%;
}
(4)css3的flexbox方法:
原理在https://www.w3cplus.com/blog/666.html里面有介绍,这里直接使用即可。
.father {
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: center;
display: -o-box;
-o-box-orient: horizontal;
-o-box-pack: center;
display: -ms-box;
-ms-box-orient: horizontal;
-ms-box-pack: center;
display: box;
box-orient: horizontal;
box-pack: center;
}
(5)CSS3的fit-content方法:
“fit-content”是CSS中给“width”属性新加的一个属性值,配合margin可以实现水平居中。
.father {
width: -moz-fit-content;
width:-webkit-fit-content;
width: fit-content;
margin-left: auto;
margin-right: auto;
}