css图片水平居中
1、利用margin: 0 auto实现图片水平居中
<div style="width: 500px; height: 500px; border: green solid 1px;">
<img src="images/top.png" style="display:block; margin: 0 auto;" />
</div>
2、利用文本的水平居中属性text-align: center
<div style="text-align: center; width: 500px; height: 500px; border: green solid 1px;">
<img src="images/top.png" style="display: inline-block;" />
</div>
3、利用父元素display:flex; flex-direction:column;子元素align-self: center实现CSS水平居中。
<div style="width: 500px ; height:500px; display: flex; flex-direction:column; border: green solid 1px;">
<img src="images/top.png" style="align-self: center" />
</div>
css图片垂直居中
1、利用高==行高实现图片垂直居中
<div style="width: 500px ;height:500px; line-height:500px; border: green solid 1px;">
<img src="images/top.png" style="display: inline-block; vertical-align: middle;" />
</div>
2、利用父元素display:table,子元素display:table-cell的方式实现CSS垂直居中
<div style="width: 500px; height:500px; display: table; border: green solid 1px;">
<span style="display: table-cell; vertical-align: middle; ">
<img src="images/top.png"/>
</span>
</div>
3、利用父元素display:flex;子元素align-self: center实现CSS垂直居中。
<div style="width: 500px ; height:500px; display: flex; border: green solid 1px;">
<img src="images/top.png" style="align-self: center" />
</div>
4、利用隐藏节点实现CSS垂直居中。
<div style="width: 500px ; height:500px; border: green solid 1px;">
<div style="width:50%; height:25%;"></div>
<img src="images/top.png" style="height:50%;" />
</div>
css图片水平垂直居中
1、利用文本水平,行高垂直实现水平垂直居中
<div style="width: 500px ; height:500px; line-height:500px; text-align:center; border: green solid 1px;">
<img src="images/top.png" style="display: inline-block; vertical-align: middle;" />
</div>
2、利用绝对定位实现图片水平垂直居中
<div style="width: 500px; height:500px; position: relative; border: green solid 1px;">
<img src="images/top.png" style="width: 120px; height: 40px; position: absolute; left:50%; top: 50%; margin-left: -60px; margin-top: -20px;" />
</div>
3、移动端可以利用flex布局实现css图片水平垂直居中
<div style="width: 500px; height:500px; display: flex; justify-content: center; align-items: center; border: green solid 1px;">
<img src="images/top.png"/>
</div>
4、相对绝对,利用上下左右为0,margin:auto;实现水平垂直居中
<div style="width: 500px; height:500px; position:relative; border: green solid 1px;">
<img src="images/top.png"/ style="width:300px; height:300px; position: absolute; left:0; right:0; top:0; bottom:0; margin:auto;">
</div>
5、一个未知宽高的div,利用 transform: translate(-50%,-50%)实现水平垂直居中;
<div style="width: 500px; height:500px; position:relative; border: green solid 1px;">
<img src="images/top.png"/ style="width:300px; height:300px; position: absolute; top:50%; left:50%; transform: translate(-50%,-50%);">
</div>
网友评论