2013-12-08 141 views
0

我有以下代碼:http://jsfiddle.net/GUSE5/5/防止HTML表格

我想的是,每行有身高表高度的33%,無論內容和圖像尺寸調整到適合細胞,但沒有失去比例。

<table class="container"><tr><td> 
<table class="contents" border=1> 
    <tr> 
     <td> 
       Top content 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <img src="http://www.hdwallpapersview.com/wp-content/uploads/2013/05/free-nature-backgrounds-wallpapers.jpg" /> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      Bottom content 
     </td> 
    </tr> 
</table> 
</td></tr></table> 

CSS:

table.container { 
    width: 200px; 
    height: 300px; 
} 

table.contents { 
    width: 100%; 
    height: 100%;  
} 

table.contents tr { 
    height: 33%; 
} 

img { 
    max-width: 100%; 
    max-height: 100%; 
} 
+0

您可能需要考慮一下版權問題 –

+0

圖像僅僅是一個例子。我在我的程序中使用不同的圖像。 – Vlad

回答

1

試試這個。

設置單元格的高度:

table.contents td { 
    height: 33%; 
} 

設置單元格進行相對定位,這樣我們就可以使用絕對定位裏面:

table.contents td { 
    height: 33%; 
    position: relative; 
} 

設置你的圖像具有max-widthmax-height100%。還將其設置爲具有絕對定位,並將其固定到左上角:

img { 
    max-width: 100%; 
    max-height: 100%; 

    position: absolute; 
    top: 0; 
    left: 0; 
} 

似乎有效。 (Fiddle)

編輯:這不適用於Firefox!一個修復上來:

設置的高度tr33%到:

table.contents tr { 
    height: 33%; 
} 

設置內td是一個block元件和具有100%高度;給它相對定位:

table.contents td { 
    display: block; 
    height: 100%; 
    position: relative; 
} 

設置你的圖像具有max-width100%max-height。還將其設置爲具有絕對定位,並將其固定到左上角:

img { 
    max-width: 100%; 
    max-height: 100%; 

    position: absolute; 
    top: 0; 
    left: 0; 
} 

應該工作! (Fiddle)

+0

它只是在Chrome中工作:-(Firefox和IE發瘋... – Vlad

+0

哦親愛的!你是什麼意思的「瘋了」?我會看看我是否可以修復。編輯:哇,它真的走了我很喜歡這個內容表,它完全符合容器的要求。 – Matthew

+0

知道了!編輯它在 – Matthew

0

我想你希望從內容中刪除多餘的空間,所以內容(文字或圖片)看起來像表格單元格配件,所以我建議從CSS中刪除此:

table.contents { 
/* width: 100%; 
height: 100%; */ 
} 
+0

不,我真的希望內容表完全適合容器。 – Vlad