前言
如何讓一個DIV居中,這應該是一個簡單的問題吧?
難道有很多不同的應用場景,以及不同的寫法嗎?
登入
常見代碼示例
1、采用 margin 水準居中。
在元素的 寬度已知 的情況下,并且 小于父容器的寬度 時,能很直覺的看到它居中了。
// 普通左右居中 margin: 0 auto;
.layour-center { margin-left: auto; margin-right: auto; }
常見寫法
2、采用 text-align:center 加 display:inline-block 實作水準居中。
<style type="text/css">
.parent {
background-color: coral;
height: 200px;
padding-top:15px;
text-align: center;;
}
.child {
background-color: white;
width:100px;
height: 50px;
display: inline-block;
/* text-align:left;*/ /* 重置為預設 */
}
</style>
3、采用 絕對定位 方式,實作 水準和垂直居中 。一般常見于登入框、彈窗等應用場景。
使用 absolute 屬性時,元素的定位是相對于其最近的被定位(position 屬性設定為非 static 的元素)的父級元素或祖先元素進行計算的。如果沒有找到被定位的父級元素或祖先元素,那麼相對于文檔的 body 元素進行計算。
使用 fixed 屬性時,元素的定位是相對于浏覽器視窗的。
是以應該根據實際情況選擇具體的屬性。
<style type="text/css">
.container-login {
background-color: coral;
position: absolute;
/* position:fixed */
/**
水準居中
左邊距離50%,同時
減去自身的 寬度 的一半。
*/
width:130px;
left:50%;
margin-left:-65px;
/**
垂直居中
上邊距離50%,同時
減去自身的 高度 的一半。
*/
height:140px;
top: 50%;
margin-top:-70px;
}
</style>
相對定位/絕對定位
4、采用 flex 布局,實作 水準和垂直居中 。父容器設定軸線以實作子容器的居中。
<style type="text/css">
.parent {
background-color: coral;
display: flex;
/* 沿着主軸水準居中 */
justify-content: center;
/* 沿着交叉軸垂直居中 */
align-items: center;
/* 父容器的高度不能為auto */
height: 300px;
}
.child {
background-color: white;
/* 确定子元素的大小 */
width: 200px;
height: 100px;
}
</style>
flex
5、使用 transform ,實作 水準和垂直居中 。 -50% 表示向左/上移動元素的一半,進而實作完美居中。
<style type="text/css">
.parent {
background-color: coral;
position: relative;
height: 230px;
}
.child {
background-color: white;
position: absolute;
width:80px;
height: 80px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
人人為我,我為人人,謝謝您的浏覽,我們一起加油吧。