2016-07-04 54 views
0

用了2天的時間與此戰鬥:http://jsfiddle.net/DQFja/537/ 基本上有一個名爲「table」的父div,其中有兩個單元格。一個單元格具有子div,另一個單元格具有圖像。圖像不會像我預期的那樣顯示在div的左上角。這可以通過從sub-div中刪除「height」屬性來解決,但我需要它(div用於背景,cell1也用於背景)。一旦圖像被添加,div的高度就會延長

<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」屬性被移除,它可以按預期工作。

回答

1

表中這樣的方式垂直居中元素 表現的解決方案可能是

1)您可以添加垂直對齊:首位;到小區 2)使用絕對定位的圖像

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

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

+0

非常感謝,也做到了! – user1826208

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/

+0

謝謝!該解決方案也適用。 – user1826208