布局中經常會遇到讓一個盒子水平且垂直居中的情況,以下總結了幾種居中方法:
- margin固定寬高居中
- 負margin居中
- 絕對定位居中
- table-cell居中
- flex居中
- transform居中
- 不確定寬高居中(絕對定位百分數)
- button居中
不兼容IE低版本的可以用其他方法hack。
不多說,直接上代碼:
大多數方法的html都相同,所以寫一個了,不同的再單獨寫出來。
(demo中有代碼和效果)
HTML:
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
- margin固定寬高居中
這種定位方法,純粹是靠寬高和margin拼出來的,不靈活。
CSS:
#container {
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
width: 200px;
height: 200px;
margin: 150px 200px;
background-color: #0ff;
}
點擊查看demo
- 負margin居中
利用負的margin來進行居中,需要知道固定寬高,限制比較大。
CSS:
#container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
width: 200px;
height: 200px;
left: 50%;
top: 50%;
margin: -100px -100px;
background-color: #0ff;
}
點擊查看demo
- 絕對定位居中
利用絕對定位居中,非常常用的一種方法。
CSS:
#container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
width: 200px;
height: 200px;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: #0ff;
}
點擊查看demo
- table-cell居中
利用table-cell來控制垂直居中。
CSS:
#container {
display: table-cell;
width: 600px;
height: 500px;
vertical-align: middle;
border: 1px solid #000;
}
#box {
width: 200px;
height: 200px;
margin: 0 auto;
background-color: #0ff;
}
點擊查看demo
- flex居中
CSS3中引入的新布局方式,比較好用。缺點:IE9以及IE9一下不兼容。
CSS:
#container {
display: -webkit-flex;
display: flex;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
width: 200px;
height: 200px;
background-color: #0ff;
}
點擊查看demo
- transform居中
這種方法靈活運用CSS中transform屬性,較為新奇。缺點是IE9下不兼容。
CSS:
#container {
position: relative;
width: 600px;
height: 600px;
border: 1px solid #000;
margin: auto;
}
#box {
position: relative;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
background-color: #0ff;
}
點擊查看demo
- 不確定寬高居中(絕對定位百分數)
這種不確定寬高的居中,較為靈活。只需要保證left和right的百分數一樣就可以實現水平居中,保證top和bottom的百分數一樣就可以實現垂直居中。
CSS:
#container {
position: relative;
width: 600px;
height: 500px;
border: 1px solid #000;
margin: auto;
}
#box {
position: absolute;
left: 30%;
right: 30%;
top: 25%;
bottom: 25%;
background-color: #0ff;
}
點擊查看demo
- button居中
利用button做外容器,里邊的塊元素會自動垂直居中,只需要控制一下水平居中就可以達到效果。
HTML:
<button>
<div></div>
</button>
CSS:
button {
width: 600px;
height: 500px;
border: 1px solid #000;
}
div {
width: 200px;
height: 200px;
margin: 0 auto;
background-color: #0ff;
}
點擊查看demo