zoukankan      html  css  js  c++  java
  • 未知宽高的图片水平垂直居中的几种方法

    最近在项目中遇到不固定宽高的图片要水平垂直居中的情况,发现垂直居中存在兼容性问题,下面收集了一些方法,可根据需要权衡使用。

    1. 背景法(兼容性好,简单,但不利于动态导入的图片)

    html:

    <div class="wrap"></div>

    css:

    .wrap{
        width:300px;
        height:200px;
        background: url(../img/test.jpg) center center no-repeat;
    }

    2. 图片外面用个p标签,通过设置line-height使图片垂直居中(兼容性较好)

    html:

    <div class="wrap">
        <img src="./img/test.jpg">
    </div>

    css:

    .wrap{
        width: 300px;
        height: 300px;
        border: 1px solid #000;
        text-align: center;
    }
    .wrap p{
        width: 300px;
        height: 300px;
        line-height: 300px;
    }
    .wrap p img{
        *margin-top:expression((300 - this.height )/2);
        vertical-align: middle;
    }        

    3. 利用display:table-cell(不兼容IE6、7)

    html:

    <div class="wrap">
        <img src="./img/test.jpg">
    </div>

    css:

    .wrap{
        width: 300px;
        height: 200px;
        border: 1px dashed #ccc;
        display: table-cell; 
        vertical-align: middle;
        text-align: center;
    }

    4. 添加table标签(兼容性好,但是冗余标签比较多)

    html:

    <div class="wrap">
        <table>
            <tr>
                <td align="center"><img src="./img/test.jpg"/></td>
            </tr>
        </table>
    </div>

    css:

    .wrap{
        width: 300px;
        height: 200px;
        border: 1px dashed #ccc;
        text-align: center;
    }
    .wrap table{
        width: 300px;
        height: 200px;
    }   
  • 相关阅读:
    抽象类
    处理网络问题的几种方法
    File类
    计算机专业的学生要怎样做才能避免成为低级的码农(转自TechFlow2019)
    java集合类
    分享一位程序员的时间管理
    WP7 操作XML文件
    C#和C/C++指针实现swap交换
    [置顶] IList接口数据动态、递归生成TreeView
    产生随机数
  • 原文地址:https://www.cnblogs.com/sapho/p/6295893.html
Copyright © 2011-2022 走看看