添加图像后,Div的高度会立即延长

时间:2016-07-04 16:55:52

标签: html css

花了2天时间与此作斗争:http://jsfiddle.net/DQFja/537/ 基本上有一个名为“table”的父div和其中的2个单元格。一个单元具有子div,另一个单元具有图像。正如我所料,图像不会显示在div的左上角。这可以通过从子div中删除“height”属性来修复,但我需要它(div用于背景,cell1也用于背景)。

<div id="table">
 <div id="cell1">
  <div id="sub-cell1">
  </div>
 </div>
 <div id="cell2">
  <img src="https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" height="20"/>
 </div>
</div>

#table
{
 display:table;
 height:103px;
}

#cell1, #cell2
{
 display:table-cell;
}

#cell1
{
 width:50%;
 height:103px;
 background-color:green;
}

#sub-cell1
{
 width:100%;
 height:103px;
 display:inline-block;
}

#cell2
{
 width:1000px;
 height:103px;
 background-color:red;
}

有人能解释一下为什么图像没有位于第二个div的左上角吗?如果删除图像或删除子div或删除子div的“height”属性,它将按预期工作。

2 个答案:

答案 0 :(得分:1)

表以这种方式表现为垂直居中元素 解决方案可能是

1)你可以添加vertical-align:top;到细胞 2)使用图像的绝对定位

#cell2
{
 width:1000px;
 height:103px;
 background-color:red;
 vertical-align: top;
}

http://jsfiddle.net/DQFja/539/

答案 1 :(得分:0)

尝试以下方法:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            .table {
                display: table;
                width: 100%;
            }

            .tableRow {
                display: table-row;
            }

            .tableCell {
                display: table-cell;
                height: 103px;
            }

            .tableCell:first-child {
                background-color: green;
                width: 50%;
            }

            .tableCell:last-child {
                background-color: red;
            }

            img {
                height: 20px;
            }
        </style>
    </head>
    <body>
        <div class="table">
            <div class="tableRow">
                <div class="tableCell">
                    <div class="subDiv">

                    </div>
                </div>

                <div class="tableCell">
                    <img src="https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="" />
                </div>
            </div>
        </div>
    </body>
</html>

https://jsfiddle.net/8r262g29/