開發時遇到一個狀況:一個用來做頁首橫幅的表格,中間那格設了背景圖,卻怎麼樣都鋪不滿。原始程式碼大致如下(index.jsp):
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8" language="java" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>讓表格百分之一百顯示</title> </head> <body style="background:#9C9;"> <table cellpadding="0" cellspacing="0" style="width:100%;" > <tr> <td height="8" width="17px;" ><img src="img/bg-header_l.gif" width="17" height="8" /></td> <td style="background:url(img/bg-header_c.gif) repeat-x;"></td> <td height="8" width="17px;" ><img src="img/bg-header_r.gif" width="17" height="8" /></td> </tr> </table> </body> </html>
執行後的畫面如下:

td 的背景沒有鋪滿整個儲存格。百思不得其解。先試著幫 table 加上 border="0",畫面沒有變化;把 0 改成 1 之後,table 確實撐滿了整個螢幕,td 的背景也鋪滿了:

但這樣一來表格多出了邊框,並不是我們要的結果,等於沒有從根本解決問題。
接著回頭對照這三個 td,才發現中間那格完全沒有內容。於是試著放點東西進去:
<table cellpadding="0" cellspacing="0" style="width:100%;" > <tr> <td height="8" width="17px;" ><img src="img/bg-header_l.gif" width="17" height="8" /></td> <td style="background:url(img/bg-header_c.gif) repeat-x;">第二個td添加內容</td> <td height="8" width="17px;" ><img src="img/bg-header_r.gif" width="17" height="8" /></td> </tr> </table>
結果基本符合預期:

只要再微調一下,把塞進去的文字隱藏起來即可:
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8" language="java" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>讓表格百分之一百顯示</title> </head> <body style="background:#9C9;"> <table cellpadding="0" cellspacing="0" style="width:100%;" > <tr> <td height="8" width="17px;" ><img src="img/bg-header_l.gif" width="17" height="8" /></td> <td style="background:url(img/bg-header_c.gif) repeat-x; font-size:0px;"> </td> <td height="8" width="17px;" ><img src="img/bg-header_r.gif" width="17" height="8" /></td> </tr> </table> </body> </html>
關鍵在於放一個 當佔位內容,再用 font-size:0px; 讓它看不見。這樣儲存格有了實際內容可供撐開,背景自然就能鋪滿,表格寬度也會正常填滿容器。
