頁面元素居中

居中

水平居中:

1.對于inline元素:為父元素設置text-align: center;即可(子元素所有內容都會居中,所以最好在子元素中使用text-align:left;歸位)。

2.對于block元素:為元素設置寬度,再設置margin: 0 auto;(IE6還是需要在父元素設置text-align: center;)

3.對于float元素:為元素設置寬度,再設置position:relative;,再設置left:50%;,最后margin-left設置為該元素寬度的一半乘以-1。

.content { height: 30px;background-color: rgb(89, 157, 197); /* 無關緊要的代碼 */ float: left; width: 300px; position: relative; left: 50%; margin-left: -150px; }

4.對于position:absolute元素:

法一:為元素設置寬度,再設置left:50%;,最后margin-left設置為該元素寬度的一半乘以-1。

法二:為元素設置寬度,再設置左右偏移為0(left: 0;和right: 0;),最后設置左右外邊距為margin: 0 auto;。

垂直居中:

1.對于單行文本垂直居中:設置高度,再設置line-height值等于設置的高度值。

2.父容器高度不知,兩種方法:

法一:父容器設置position:relative;,子容器設置position: absolute; top: 50%; transform: translateY(-50%);。

.main { position: relative; width:100%;height: 500px;background-color: rgb(199, 196, 43); /* 無關緊要的代碼 */ } .content { background-color: rgb(89, 157, 197); /* 無關緊要的代碼 */ position: absolute; top: 50%; transform: translateY(-50%); }

法二:(父容器下只有這個子元素時使用)子容器設置position: relative; top: 50%; transform: translateY(-50%);。

.main { width:100%;height: 500px;background-color: rgb(199, 196, 43); /* 無關緊要的代碼 */ } .content { background-color: rgb(89, 157, 197); /* 無關緊要的代碼 */ position: relative;top: 50%; transform: translateY(-50%); }

注:transform: translate中的translate是根據自身百分比寬高在X/Y軸上移動。所以如果在子元素使用position: absolute;left:50%; transform:translate(-50%,0);則可以實現水平居中。

3.flex簡單粗暴:

.main{ width: 100%; height: 400px; background-color: aqua; /* 無關緊要的代碼 */ display:flex;/*Flex布局*/ display: -webkit-flex; /* Safari */ align-items:center;/*指定垂直居中*/ // justify-content:center; /*指定水平居中*/ } .content { width: 200px;height: 200px;background-color: rgb(89, 157, 197); /* 無關緊要的代碼 */ }

【個人筆記,只作分享討論】

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容