CSS实现盒子居中分为两个步骤,一个是水平居中,另一个是垂直居中。
以下介绍各种使盒子居中的方法
1:计算并设置内外边距
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
padding-top: 100px;
padding-left: 100px;
padding-right: 100px;
padding-bottom: 100px;
}
.di2{
width:500px;
height:500px;
background-color: navajowhite;
}
</style>
</head>
<body>
<div class="di1">
<div class="di2">
</div>
</div>
这个确实简单,但设置外边距时可能导致外边距合并,需要注意。
2:利用绝对定位锁定居中位置,并用transform将盒子移动到中央。(免计算,解放大脑)
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
position: relative;
}
.di2{
width:500px;
height:500px;
background-color: navajowhite;
position: absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
</style>
<div class="di1">
<div class="di2">
</div>
</div>
3.绝对定位至盒子左上角在大的盒子中心。设置margin
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
position: relative;
}
.di2{
width:300px;
height:300px;
background-color: navajowhite;
position: absolute;
left:50%;
top:50%;
margin-top:-150px;
margin-left:-150px;
}
</style>
<div class="di1">
<div class="di2">
</div>
</div>
4.绝对定位时上下左右设为0,margin为auto。
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
position: relative;
}
.di2{
width:300px;
height:300px;
background-color: navajowhite;
margin:auto;
position: absolute;
left:0;
top:0;
bottom: 0;
right:0;
}
</style>
<div class="di1">
<div class="di2">
</div>
</div>
5.设置为弹性盒子并设置align-items(垂直方向)justify-content(水平方向)取值为center
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
display: flex;
align-items:center;
justify-content: center;
}
.di2{
width:300px;
height:300px;
background-color: navajowhite;
}
</style>
<div class="di1">
<div class="di2">
</div>
</div>
6.先将要居中的盒子设为行块盒。再用text-align设置为水平居中,用padding-top设置为垂直居中(由于设置padding后盒子高度会变化,可以把display设置为border-box)。
<style>
.di1{
width:500px;
height:500px;
background-color: yellow;
box-sizing: border-box;
text-align: center;
padding-top:100px;
}
.di2{
width:300px;
height:300px;
background-color: navajowhite;
display: inline-block;
}
</style>
<div class="di1">
<div class="di2">
</div>
</div>
好的,一共六种方式,其中比较省心简单的方法应该是先设置定位再tranform转化到中央。
具体读者可自行选择。