示例代碼:
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: white;
}
</style>
<body>
<div class="box">
<div class='inner'>
居中
</div>
</div>
</body>
水平居中
1.<center>
標籤
最簡單的方法,只需要在<div>
外加上<center>
就可以讓<div>
水平居中:
代碼:
<body>
<div class="box">
<center>
<div class='inner'>
居中
</div>
</center>
</div>
</body>
效果:
2.margin法
將<div>
的 margin (外邊距)屬性設置成 “0 auto” 就可以居中
代碼:
.inner {
width: 100px;
height: 100px;
background-color: white;
margin: 0 auto;
}
效果:
3.絕對位置法
將<div>
設置成絕對佈局,然後用left或right移動<div>
到中間,由於元素的座標原點是左上角,所以爲了居中,要移回半個<div>
寬度的距離。
可以用margin-left:[1/2寬度]px
或者transform: translate(-50%,0)
實現
需要注意的是使用這種方法時,必須定義了位置佈局方式。
代碼:
.box {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: white;
position: absolute;
left: 50%;
margin-left: -50px;
}
效果:
垂直居中
1.margin法
垂直居中也可以用margin實現,同樣需要聲明佈局方式。
代碼:
.box {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.inner {
position: absolute;
width: 100px;
height: 100px;
background-color: white;
margin: auto;
top: 0;
bottom: 0;
}
效果:
2.絕對位置法
和水平居中一樣 把left改爲top即可
代碼:
.box {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: white;
position: absolute;
top: 50%;
margin-top: -50px;
}
效果:
同時居中
1.margin法
只需margin:auto;
, 然後top
、 left
、right
、bottom
設置爲相同值即可
代碼:
.box {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: white;
position: absolute;
margin: auto;
top:0;
bottom: 0;
left: 0;
right: 0;
}
效果:
2.絕對位置法
將水平居中垂直居中同時使用即可。
代碼:
.box {
position: relative;
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
效果: