在表格儲存格放置圖片是電商後台、產品目錄、會員名單常見需求。本文涵蓋 <img> 基礎用法、響應式縮放、垂直置中、載入優化(lazy/webp)、錯誤備援與無障礙完整實務。
<table>
<tr>
<th>產品</th><th>圖片</th><th>價格</th>
</tr>
<tr>
<td>筆記型電腦</td>
<td><img src="laptop.jpg" alt="銀色筆記型電腦" width="120" height="90"></td>
<td>NT$ 35,000</td>
</tr>
</table>
必要屬性:
src:圖片網址(相對/絕對/資料 URI)alt:替代文字(**必填**,無障礙/SEO/圖片失效時顯示)width/height:預留空間,防止版面跳動(CLS 優化)<style>
.responsive-img {
max-width: 100%; /* 不超過儲存格寬度 */
height: auto; /* 保持比例 */
display: block; /* 消除底部間隙 */
}
td.img-cell { padding: 4px; } /* 給圖片留邊距 */
</style>
<td class="img-cell"><img class="responsive-img" src="product.jpg" alt="產品圖"></td>
<style>
td { vertical-align: middle; } /* 預設即為 middle,但被 reset 時需補回 */
.img-cell { text-align: center; } /* 水平置中 */
</style>
<img src="photo.jpg" alt="..." loading="lazy" width="200" height="150">
瀏覽器在圖片進入視口前不下載,**大幅降低首屏流量**。
<picture>
<source type="image/avif" srcset="photo.avif">
<source type="image/webp" srcset="photo.webp">
<img src="photo.jpg" alt="產品照片" width="200" height="150" loading="lazy">
</picture>
<img src="photo-1x.jpg"
srcset="photo-1x.jpg 1x, photo-2x.jpg 2x, photo-3x.jpg 3x"
alt="產品照片" width="200" height="150" loading="lazy">
<img src="photo.jpg" alt="產品" onerror="this.onerror=null; this.src='placeholder.png';">
| 模式 | CSS 關鍵 | 適用場景 |
|---|---|---|
| 縮圖列表 | width:60px; height:60px; object-fit:cover; border-radius:4px; | 商品、會員頭像 |
| 寬幅橫幅 | width:100%; height:auto; max-height:200px; object-fit:cover; | 活動、新聞列表 |
| 圖文混排 | vertical-align:middle; max-width:100%; | 說明文件、規格表 |
| 圖片畫廊 | display:grid; grid-template-columns:repeat(auto-fill, 80px); gap:4px; | 多圖欄位 |
alt="")<figcaption> 或 longdesc 連結onerror)aria-label)public, max-age=31536000, immutable掌握 <img> 進階屬性與 <picture>、srcset、loading=lazy 現代技術,讓表格圖片既美觀又高效、無障礙。下次在表格放圖片時,記得加上 width/height、loading=lazy 與有意義的 alt!