DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
表格設背景圖片無法鋪滿整個儲存格?真正原因在這裡
編輯:HTML和Xhtml     

開發時遇到一個狀況:一個用來做頁首橫幅的表格,中間那格設了背景圖,卻怎麼樣都鋪不滿。原始程式碼大致如下(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>

執行後的畫面如下:

兩個不對的地方

  1. 中間那個 td 的背景沒有鋪滿整個儲存格。
  2. 整個 table 的寬度沒有撐滿螢幕。

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

但這樣一來表格多出了邊框,並不是我們要的結果,等於沒有從根本解決問題。

真正的原因:空的 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;">&nbsp;</td>
<td height="8" width="17px;" ><img src="img/bg-header_r.gif" width="17" height="8" /></td>
</tr>
</table>
</body>
</html>

關鍵在於放一個 &nbsp; 當佔位內容,再用 font-size:0px; 讓它看不見。這樣儲存格有了實際內容可供撐開,背景自然就能鋪滿,表格寬度也會正常填滿容器。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved