css设置图片垂直居中的方法:

一、使用flex实现垂直居中

利用css flex实现垂直居中,有些浏览器可能不兼容flex。

首先要创建一个包裹着图片的div元素,然后定义基础属性。

以下图片img宽度为(设置为)100px,高度为100px。

HTML代码部分:

<style>
.flexbox{width: 300px;height: 250px;background:#ccc;display: flex;align-items: center;text-align:center; }
.flexbox img{width: 100px;height: 100px;margin:0 auto;}
</style>
<div class="flexbox">
<img src="img.png" alt="">
</div>

 

 

二、利用Display: table;实现img图片垂直居中 

1、先创建一个div元素以及另外一个包含图片的div元素,设置样式

2、给img父元素设置display:table

3、包裹图片的父类div元素设置display:table-cell

<style>
.tablebox{width: 300px;height: 300px;background: #fff;display: table;background: #ccc;}
#imgbox{display: table-cell;vertical-align: middle;    text-align: center;}
#imgbox img{width: 100px;}
</style>

<div class="tablebox">
<div id="imgbox">
<img src="img.png" alt="">
</div>
</div>

 

 三、用绝对定位实现垂直居中

 

<style>

.posdiv{width: 300px;height: 300px;background: #eee;position: relative; text-align:center; }
.posdiv img{width: 100px;position: absolute;top: 50%;margin-top: -50px;margin-left: -50px;}
</style>
<div class="posdiv">
<img src="img.png" alt="">
</div>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐