盒子如下
<div class="parent">
<div class="box" id="box">
盒子
</div>
</div>
1)利用定位(常用方法,推荐)
盒子需要固定的宽高,且需要定位
<style>
body {
height: 100%;
overflow: hidden;
background-color: blanchedalmond;
}
.box {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
line-height: 100px;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -50px;
}
</style>
2)method2 利用 margin:auto;
盒子需要固定的宽高,且需要定位
body {
height: 100%;
overflow: hidden;
background-color: blanchedalmond;
}
.box {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
line-height: 100px;
text-align: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3)method3 利用 transform。
不需要盒子具体宽高,但需要定位,兼容性不好
body {
height: 100%;
overflow: hidden;
background-color: blanchedalmond;
}
.box {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
line-height: 100px;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
4)method4
利用 display:flex;设置垂直水平都居中
html
{
width: 100%;
height: 100%;
background-color: blanchedalmond;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
line-height: 100px; /* 文本垂直居中 */
text-align: center; /* 文本水平居中 */
}
5)method5 :
display:table-cell
.parent {
width: 400px;
height: 400px;
background-color: blanchedalmond;
text-align: center;
vertical-align: middle;
display: table-cell;
}
.box {
width: 100px;
height: 100px;
border: 1px solid red;
box-sizing: border-box;
line-height: 100px;
display: inline-block;
}