一、定位加margin:auto;
<style>
.out{
width: 300px;
height: 300px;
background-color: bisque;
position: relative;
}
.in{
width: 100px;
height: 100px;
background-color: aqua;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
二、flex布局/grid布局+主轴与交叉轴对齐方式
<style>
.out{
display: flex;
width: 300px;
height: 300px;
background-color: bisque;
/* 或者 */
/* display: grid; */
/* 设置主轴对齐方式 */
justify-content: center;
/* 设置交叉轴对齐方式 */
align-items: center;
}
.in{
width: 100px;
height: 100px;
background-color: lightcoral;
}
</style>
三、flex+外边距
<style>
.out{
display: flex;
width: 300px;
height: 300px;
}
.in{
width: 100px;
height: 100px;
background-color: lightcoral;
margin: auto;
}
</style>
四、边框盒子+内边距
<style>
.out{
width: 400px;
height: 400px;
background-color: bisque;
box-sizing: border-box;
/* 内边距设置为父元素宽度减子元素盒子宽度的差的一半 */
padding: 150px;
}
.in{
width: 100px;
height: 100px;
background-color: lightgreen;
}
</style>
五、定位+两边外边距
<style>
.out{
position: relative;
width: 300px;
height: 300px;
background-color: palegreen;
}
.in{
position: absolute;
width: 100px;
height: 100px;
background-color: palevioletred;
top: 50%;
left: 50%;
margin-left:-50px;
margin-top:-50px;
}
</style>