508 字
3 分鐘

CSS 圖片底部有空隙?量出 inline 圖片的基線空間

本文目錄

圖片明明貼齊上緣,底下卻露出一條父容器背景,調整 margin 和 padding 也無效。先看 img 是否仍是 inline。行內圖片預設對齊文字基線,行盒底部還可能留給像 g、p 這類字母的下緣。 獨立顯示的卡片圖片可以設 display: block;圖片要跟文字留在同一列時,選擇合適的 vertical-align。行盒與對齊規則見 CSS 2.2 行高計算。

用同一張圖片量底部空隙#

存成 HTML 後直接開啟。範例使用實心圖片和沒有邊框、外距、內距的容器,讓量測只反映行內排版。下方數字以 CSS 像素表示。

<!doctype html>
<meta charset="utf-8">
<title>圖片基線空隙</title>
<style>
.frame {
width: 96px;
background: #efaa77;
font: 16px/24px Arial, sans-serif;
}
.block img { display: block; }
.bottom img { vertical-align: bottom; }
</style>
<p>行內圖片</p>
<div class="frame"><img width="96" height="48" alt=""
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"></div>
<p>區塊圖片</p>
<div class="frame block"></div>
<p>行內圖片,貼齊行盒底部</p>
<div class="frame bottom"></div>
<pre id="result"></pre>
<script>
const frames = [...document.querySelectorAll('.frame')];
for (const frame of frames.slice(1)) {
frame.append(frames[0].firstElementChild.cloneNode());
}
const gaps = frames.map(frame => {
const image = frame.firstElementChild.getBoundingClientRect();
return frame.getBoundingClientRect().bottom - image.bottom;
});
document.querySelector('#result').textContent = JSON.stringify(gaps);
</script>

在 macOS 的 Chrome 158.0.8127.89,三組量到 7px、0px、0px。第一組的大小隨字型和行高變化。第二組的圖片是區塊,這個容器裡沒有文字行盒需要保留。第三組仍使用行盒,vertical-align: bottom 把圖片下緣對齊行盒下緣。混排時對齊方式也會影響文字和其他行內元素的位置,可用實際文案確認字級變更或換行後的結果。

看空隙在圖片盒的哪一側#

在 DevTools 選取 img,如果高亮邊界停在空隙上方,先在 Styles 面板切換 display: block,並檢查行盒、容器內距和圖片外距。圖片已經是 block 時,確認量到的容器是否真的是產生背景的那一層。若高亮範圍整片蓋住留白,檢查原圖透明像素、圖片盒尺寸與 object-fit 的裁切和留白。

參考資料:

W3C:CSS 2.2 Line height calculations

MDN:vertical-align

CSS 圖片底部有空隙?量出 inline 圖片的基線空間
https://laplusda.com/posts/css-inline-image-bottom-gap/
作者
Zero
發佈於
2026-11-30
許可協議
CC BY-NC-SA 4.0