<div class="box">
<img src="./1.jpg" alt=""/>
</div>
第一种:水平居中
.box {
width:300px;
height:300px;
border:2px solid red;
}
img{
display:block;
width:100px;
height:100px;
margin:0 auto;
}
第二种:水平居中
.box{
width:300px;
height:300px;
border:2px solid red;
text-align:center;
}
img{
width:100px;
height:100px;
display:inline-block;
}
第三种:水平垂直居中 定位+需要居中元素的margin减去宽高的一半(取负值)
.box {
width:300px;
height:200px;
border:1px solid red;
position:relative;
}
img{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
}
第四种:水平垂直居中 定位+margin:auto
.box{
width:300px;
height:200px;
border:1px solid red;
position:relative;
}
img{
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
margin:0 auto;
}
第五种:水平垂直居中 定位+transform
.box {
width:300px;
height:200px;
position:relative;
border:1px solid red;
}
img{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
第六种:水平垂直居中 display:table-cell
.box{
width:300px;
height:200px;
border:2px solid red;
display:table-cell;
verticall-align:middle;
text-align:center;
}
img{
width:100px;
height:100px;
}
.box-table{
display:table
}
<div class="box-table">
<div class="box">
<img src="./1.jpg" alt=""/>
</div>
</div>
第七种:垂直水平居中 flex
.box{
width:300px;
height:200px;
border:1px solid red;
display:flex;
justify-content:center;
align-items:center;
}
img{
width:100px;
height:100px;
}