user1826208
user1826208

Reputation: 73

Div's height gets extended as soon as an image is added

Spent 2 days fighting with this: http://jsfiddle.net/DQFja/537/ Basically have a parent div called "table" and 2 cells in it. One cell has sub-div, another cell has an image. Image is not displayed on the top left side of the div as I would've expected. This can be fixed by removing "height" attribute from the sub-div but I need it (the div is used for background and cell1 is also used for background).

<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;
}

Could anybody explain me why the image is not positioned on the top left side in the second div here? It works as expected if image is removed or if the sub-div is removed or if "height" attribute of the sub-div is removed.

Upvotes: 0

Views: 53

Answers (2)

Mers
Mers

Reputation: 734

Try the following:

<!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/

Upvotes: 0

Sergey Khmelevskoy
Sergey Khmelevskoy

Reputation: 2544

table behave in such way to center elements vertically The solutions might be

1) you can add vertical-align: top; to the cell 2) use absolute positioning for the image

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

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

Upvotes: 1

Related Questions