1.水平居中的margin:0 auto;
设置块元素(或与之类似的元素)的居中。
注意:margin:0 auto;的选择器是作用对象(子元素),如div,p,而不是body。且不受float影响(设置display: block)。
2.水平居中text-align:center;
3.水平垂直居中:
(1)定位和需要定位的元素的margin减去宽高的一半
img{
width: 100px;
height: 150px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;
margin-left: -50px;
}
(2)定位和margin:auto;
auto设置左右边距为来使其水平居中。元素会占据你所指定的宽度,然后剩余的宽度会一分为二成为左右外边距
img{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
(3)绝对定位和transfrom
transform:translate(-50%,-50%):向上(X轴)向左(Y轴)移动自身长宽的50%,使其位于中心。同理,需要按比例移动元素的话修改translate的值就可以做到。
注意:需要居中的元素应为绝对定位(position: absolute;)
img{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
(4)display:table-cell
把其变成表格样式,再利用表格的样式来进行居中,很方便
.box{
width: 300px;
height: 300px;
background:#e9dfc7;
border:1px solid red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
(5)flexBox(伸缩容器)居中
用了CSS3新特性flex,非常方便快捷,在移动端使用完美,pc端有兼容性问题(只有谷歌和火狐支持)
.container{
display:flex;
flex-flow:row;
}
.main{
width:60%;
}
.left{
flex:1;
}
right{
flex:2;
}
最后附加一个总结对比比较详细的博客链接:https://blog.youkuaiyun.com/freshlover/article/details/11579669