水平垂直居中
不定宽高
Flex
容器设置display: flex; align-items: center; justify-content: center;
<style type="text/css">
#box{
/* 关键属性:display、align-items、justify-content --START */
display: flex;
align-items: center;
justify-content: center;
/* 关键属性:display、align-items、justify-content --END */
border: 1px solid #0000FF;
height: 200px;
width: 400px;
}
.item{
width: 50px;
height: 40px;
border: 1px solid #00C1B3;
/* 文字水平垂直居中 */
display: flex;
justify-content: center;
align-items:center;
}
</style>
绝对定位
1、position:absolute,左上定位50%,transform的translate(-50%, -50%)进行定位修正。
注:translate = translateX + translateY; translate3d = translateX + translateY + translateZ。
<style type="text/css">
#box{
width: 400px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: #00C1B3;
}
</style>
2、position:absolute,左上定位50%,margin进行位置修正。
<style type="text/css">
#box{
width: 1200px;
height: 600px;
position: absolute;
left: 50%;
top: 50%;
margin: -300px 0 0 -600px;
}
</style>
3、postion: absolute, 上下左右定位设0,margin: auto。
<style>
#box {
width: 200px;
height: 200px;
background: #399d46;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>