第一种
父级:display:flex; 子级:margin:auto;【兼容性不好】
<style>
.father_box {
width: 300px;
height: 300px;
border: 1px solid #ff0000;
margin: 50px auto;
display: flex;
}
.son_box {
width: 120px;
margin: auto;
background: #ff0000;
}
</style>
<div class="father_box">
<div class="son_box">
width: 120px; margin: auto; background: #ff0000;
</div>
</div>
第二种
父级:position: relative; 子级:position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;【子级必须写高度】
<style>
.father_box {
width: 300px;
height: 300px;
border: 1px solid #ff0000;
margin: 50px auto;
position: relative;
}
.son_box {
width: 120px;
height: 180px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: #ff0000;
}
</style>
<div class="father_box">
<div class="son_box">
width: 120px; position: absolute; top: 0; left: 0; right: 0; bottom: 0;
margin: auto; background: #ff0000;
</div>
</div>
第三种
父级:position: relative; 子级:position: absolute;top: 50%; left: 50%;margin: -(高的一半)px -(宽的一半)px;【子级必须设置高】
<style>
.father_box {
width: 300px;
height: 300px;
border: 1px solid #ff0000;
margin: 50px auto;
position: relative;
}
.son_box {
width: 120px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin: -100px -60px;
background: #ff0000;
}
</style>
<div class="father_box">
<div class="son_box">
width: 120px; height: 200px; position: absolute; top: 50%; left: 50%;
margin: -100px -60px; background: #ff0000;
</div>
</div>
第四种
父级:position: relative; 子级:position: absolute;top: 50%; left: 50%;transform: translate(-50%, -50%);【兼容性不好】
<style>
.father_box {
width: 300px;
height: 300px;
border: 1px solid #ff0000;
margin: 50px auto;
position: relative;
}
.son_box {
width: 120px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #ff0000;
}
</style>
<div class="father_box">
<div class="son_box">
width: 120px; position: absolute; top: 50%; left: 50%;
transform: translate(-50%, -50%); background: #ff0000;
</div>
</div>
第五种
父级:display: flex;align-items: center;justify-content: center; 【兼容性不好】
<style>
.father_box {
width: 300px;
height: 300px;
border: 1px solid #ff0000;
margin: 50px auto;
display: flex;
align-items: center;
justify-content: center;
}
.son_box {
width: 120px;
background: #ff0000;
}
</style>
<div class="father_box">
<div class="son_box">
width: 120px; background: #ff0000;
</div>
</div>