在我们的web前端css开发过程中,我们避免会遇到让图片居中的情况,为了网页美观以及用户的体验,我们有时候就要让图片居中,那么我们也都知道图片居中的方法有很多,今天我们就给大家详细介绍下css实现图片居中的三种方式!
1.利用display:table-cell,具体代码如下:
html代码如下:
1 <p class="img_wrap"> 2 <img src="wgs.jpg"> 3 </p>
css代码如下:
1 .img_wrap{
2 width: 400px;
3 height: 300px;
4 border: 1px dashed #ccc;
5 display: table-cell; //主要是这个属性
6 vertical-align: middle;
7 text-align: center;
8 }效果如下:
立即学习“前端免费学习笔记(深入)”;

2.采用背景法:
html代码如下:
1 <p class="img_wrap"></p>
css代码如下:
.img_wrap{
width: 400px;
height: 300px;
border: 1px dashed #ccc;
background: url(wgs.jpg) no-repeat center center;
}效果如下图:

3.图片外面用个p标签,通过设置line-height使图片垂直居中:
html代码如下:
1 <p class="img_wrap"> 2 <p><img src="wgs.jpg"></p> 3 </p>
css代码如下:
1 *{margin: 0px;padding: 0px}
2 .img_wrap{
3 width: 400px;
4 height: 300px;
5 border: 1px dashed #ccc;
6 text-align: center;}
7 .img_wrap p{
8 width:400px;
9 height:300px;
10 line-height:300px; /* 行高等于高度 */
11 }
12 .img_wrap p img{
13 *margin-top:expression((400 - this.height )/2); /* CSS表达式用来兼容IE6/IE7 */
14 vertical-align:middle;
15 border:1px solid #ccc;
16 }效果图如下:

总结:
图片居中的方法有很多种,我们这里为大家介绍了常用的三种方式,小伙伴们可以根据自己的需求选择适合自己的方法、希望对你的工作有所帮助!
相关推荐:
以上就是CSS实现图片居中的三种方式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号