好比a,b,strong,i,span,img,input,select
等, 爲父元素設置text-align: center;
便可。css
好比div,p,ul,li,ol,h1-h6,dl,dt,dd,address,article
等bash
width: 固定;
margin: 0 auto;
複製代碼
display: flex;
flex-direction:row; /*設置主軸方向爲水平方向(默認)*/
justify-content: center; /*主軸對齊方式*/
複製代碼
兼容性:IE8/9不支持。flex
.parent{ position: relative;}
.son{
position:absolute;
top: 50%;
left: 50%;
/*往上(x軸),左(y軸)移動自身長寬的 50%,以使其居於中心位置。*/
transform:translate(-50%, -50%);
}
複製代碼
兼容性:IE8不支持。ui
position: absolute; /*注意絕對定位*/
width: 固定;
left: 50%; /*偏移量設置爲50%*/
margin-left: -0.5寬度; /* -寬度/2*/
複製代碼
left:0; right:0; margin:0 auto;
position: absolute;
width: 固定;
left: 0;
right: 0;
margin: 0 auto;
複製代碼
設置line-height
等於父元素的高度。spa
這種方法只適用於單行文本的元素,好比塊級元素裏面文本、圖片。code
給元素設置display:inline-block;
屬性,須要使用一個僞元素讓內容塊處於容器的中央, 注意要給這個僞類高度設置高度100%。orm
.parent::after, .son{ /*父級元素和子元素都設置display:inline-block*/
display:inline-block;
vertical-align: middle; /*設置vertical-align:middle*/
}
.parent::after{ /*父元素添加一個僞類,而且設置高度100%*/
content:"";
height:100%;
}
複製代碼
兼容性:IE6及如下不可用圖片
display: flex;
align-items: center; /*居中*/
複製代碼
position: absolute;
top: 50%;
height: 固定;
margin-top: -0.5高度;
複製代碼
top:0; bottom:0; margin:0 auto;
position:absolute;
height:固定;
top:0;
bottom:0;
margin:auto 0;
複製代碼
flex, transform, 絕對定位 這幾種方法同時適用於水平居中和垂直居中。input