1、定位:子绝父相之后,给子元素div添加上下左右为0,外边距为auto。
.box{
width:300px;
height:300px;
border:1px solid #333;
position: relative;
}
div{
width:10px;
height: 10px;
position: absolute;
top: 0;
left: 0;
right:0;
bottom:0;
margin:auto;
}
2、left和top都为50%,并让元素向左、向上平移50%。
.small{
width: 100px;
height: 100px;
background-color: #00f;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
transform: translate(-50%, -50%);
}
3、弹性盒(因为兼容问题弹性盒一般用于手机端,PC端不用)
justify-content: center;
align-items: center;
4、将小div转成行内块元素:在小div后,新增span标签(或是其他行内标签i/em等),给小盒子设置vertical-align:middle,给大盒子设置line-height为大盒子高度,并写上text-align:center;
.box{
width: 500px;
height: 500px;
border: 3px solid #f00;
position: relative;
text-align: center;
line-height: 500px;
}
.small{
width: 100px;
height: 100px;
background-color: #00f;
display: inline-block;
/*
修饰的是行内块
垂直的对齐方式
参考谁进行垂直对齐 - 当前行
*/
vertical-align: middle;
}
5、使用网格布局
<style>
.small{
width: 100px;
height: 100px;
background-color: #f00;
grid-area: a;
}
.box{
width: 300px;
height: 300px;
border: 1px solid #000;
display: grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
grid-template-areas: ". . ." ". a ." ". . .";
}
</style>
<div class="box">
<div class="small"></div>
</div>