水平居中和垂直居中

水平居中

若元素爲inline元素

好比a,b,strong,i,span,img,input,select等, 爲父元素設置text-align: center; 便可。css

若元素爲block元素

好比div,p,ul,li,ol,h1-h6,dl,dt,dd,address,articlebash

width: 固定;
margin: 0 auto;
複製代碼

使用flex

display: flex; 
flex-direction:row; /*設置主軸方向爲水平方向(默認)*/
justify-content: center; /*主軸對齊方式*/
複製代碼

兼容性:IE8/9不支持。flex

使用CSS3中新增的transform屬性

.parent{ position: relative;}
.son{ 
  position:absolute; 
  top: 50%;
  left: 50%; 
  /*往上(x軸),左(y軸)移動自身長寬的 50%,以使其居於中心位置。*/
  transform:translate(-50%, -50%);
}
複製代碼

兼容性:IE8不支持。ui

絕對定位方式

  1. 設置margin負半值
position: absolute;  /*注意絕對定位*/
width: 固定; 
left: 50%;  /*偏移量設置爲50%*/
margin-left: -0.5寬度; /* -寬度/2*/
複製代碼
  1. 設置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及如下不可用圖片

使用flex

display: flex;
align-items: center;  /*居中*/
複製代碼

絕對定位方式

  1. 設置margin負半值,且父元素爲相對定位
position: absolute; 
top: 50%; 
height: 固定; 
margin-top: -0.5高度;
複製代碼
  1. 設置top:0; bottom:0; margin:0 auto;
position:absolute;
height:固定;
top:0;
bottom:0;
margin:auto 0;
複製代碼

總結

flex, transform, 絕對定位 這幾種方法同時適用於水平居中和垂直居中。input

相關文章
相關標籤/搜索