水平容易,垂直難啊!且學且珍惜~~

先就介紹常見的三種方法,更多的居中方法可以自行百度谷歌。

目錄:
1.絕對定位+margin:auto法
2.絕對定位+margin負間距法
3.Flex彈性布局法

先順帶記一下水平居中:

  • 內聯元素水平居中:在父元素上設置 text-align : center;
  • 塊級元素水平居中:margin : 0 auto;

正文:

1. 絕對定位+margin:auto法

給父元素設置:

position:relative;//父元素相對定位

居中的元素設置:

position:absolute;//子元素絕對定位
margin:auto;
left:0;
top:0;
bottom:0;
right:0;

原理 : 定位都給0了,元素自己也不知道該去哪兒,只好待在中間不知所措...(猜)

2. 絕對定位+margin負間距法

給父元素設置:

position:relative;//父元素相對定位

居中的元素設置:

width:200px;
height:200px;
position:absolute;//子元素絕對定位
left:50%;
top:50%;
margin-left:-100px;//width的一半
margin-top:-100px;//height的一半

3. Flex彈性布局法

給父元素設置:

display: flex;
justify-content: center; /*顯示在主軸的中間*/
align-items: center; /*子項在側軸中間位置*/

其實也不是很難對不對~

End.

推薦閱讀:

相关文章