代码之家  ›  专栏  ›  技术社区  ›  Alvaro

高度:100%在表格单元格内,无法在Firefox和IE上工作

  •  19
  • Alvaro  · 技术社区  · 12 年前

    我在尝试创建 div 具有 height:100% 包在里面 display:table-cell .

    我注意到它在Firefox和IE 9中不起作用。

    Here's the fiddle with the problem 。你可以注意到它可以正常工作,Chrome或Opera也可以。

    代码出了什么问题?

    有什么办法解决吗?

    我想保留 display:table 显示:表格单元格 以使内容在可变高度容器上垂直居中。

    HTML格式

    <div class="table">
        <div class="table-cell">
            <div class="content"></div>
        </div>
    </div>
    

    CSS格式

    body, html {
        margin:0;
        padding:0;
        height:100%;
    }
    .table {
        display:table;
        width:100%;
        height:100%;
    }
    .table-cell {
        display:table-cell;
        vertical-align: middle;
        width:100%;
    }
    .content {
        height: 100%;
        display: block;
        overflow: hidden;
        position: relative;
        background: url(http://spaceinimages.esa.int/var/esa/storage/images/esa_multimedia/images/2012/11/solar_eclipse_corona/12092636-3-eng-GB/Solar_eclipse_corona_node_full_image.jpg);
        background-size:cover;
    }
    
    2 回复  |  直到 5 年前
        1
  •  29
  •   TRiG    11 年前

    对于 height:100% 要工作,所有父容器都必须 高度:100% 。如果你注意到了,你的 .table-cell 样式没有 高度:100% .

    添加此样式可以修复Firefox中的问题:

    .table-cell {
        display:table-cell;
        vertical-align: middle;
        width:100%;
        height:100%;
    }
    

    作为一种选择,将图像添加到HTML中,而不是作为CSS background-image 也可能起作用。

    body, html {
        margin:0;
        padding:0;
        height:100%;
    }
    .table {
        display:table;
        width:100%;
        height:100%;
    }
    .table-cell {
        display:table-cell;
        vertical-align: middle;
        width:100%;
    }
    .content {
        height: 100%;
        display: block;
        overflow: hidden;
        position: relative;
        background-size:cover;
    }
    
    .content img {
        width:100%;
        height:100%;
    }
    <div class="table">
        <div class="table-cell">
            <div class="content">
                <img src="http://spaceinimages.esa.int/var/esa/storage/images/esa_multimedia/images/2012/11/solar_eclipse_corona/12092636-3-eng-GB/Solar_eclipse_corona_node_full_image.jpg"/>
            </div>
        </div>
    </div>

    HTML格式

    <div class="content">
        <img src="...your image url..." />
    </div>
    

    CSS格式

    .table-cell {
        display:table-cell;
        vertical-align: middle;
        width:100%;
    }
    
    .content img {
        width:100%;
        height:100%;
    }
    
        2
  •  -3
  •   Max    10 年前

    您必须设置 .content .table .table-cell 类别如下

    .content {
        display: table;
        height: 100%;
    }
    
    .table, .table-cell {
        height: 100%;
    }