622 字
3 分鐘
CSS 圓角加了 overflow: hidden 仍裁不到子元素?檢查 absolute 定位
本文目錄
卡片的底色有圓角,蓋在上面的標籤或滿版圖片卻仍畫成直角。若卡片已經設了 overflow: hidden,先檢查滿版子元素的 position: absolute 是相對哪一層定位。當定位基準在裁切層外面,絕對定位的子元素可以跨過中間這一層的 overflow 裁切。 如果子元素應該貼齊卡片,就讓卡片同時負責定位與裁切。
用同尺寸卡片找出是哪一層生效
把下列內容存成 HTML 開啟。兩個外框都有 position: relative,尺寸也相同。左側的紅色子元素相對外框定位,右側則由加了 position: relative 的卡片接手。
<!doctype html><meta charset="utf-8"><title>圓角裁切與絕對定位</title><style> .examples { display: flex; gap: 24px; } .frame { position: relative; width: 160px; height: 100px; } .card { height: 100%; border-radius: 28px; overflow: hidden; } .fixed { position: relative; } .overlay { position: absolute; inset: 0; background: #d94737; }</style><div class="examples"> <div class="frame"> <div class="card"><div class="overlay"></div></div> </div> <div class="frame"> <div class="card fixed"><div class="overlay"></div></div> </div></div>左側紅色色塊仍然佔到左上角,右側的角落會露出頁面底色。CSS 2.2 的 overflow 規則列出了定位基準跨過裁切層的例外,CSS Backgrounds 的角落裁切規則則說明套用 overflow 裁切時如何沿著圓角走。
如果靠肉眼看不清楚,可以在 Console 檢查每張卡片。左上角往內 3px 應該在 28px 圓角外,中央則應該仍命中紅色元素。
for (const card of document.querySelectorAll('.card')) { const overlay = card.querySelector('.overlay'); const { left, top, width, height } = card.getBoundingClientRect(); console.log({ positionedBy: overlay.offsetParent.className, cornerHitsOverlay: document.elementFromPoint(left + 3, top + 3) === overlay, centerHitsOverlay: document.elementFromPoint(left + width / 2, top + height / 2) === overlay, });}在這個簡化的 HTML 中,預期第一張顯示 frame / true / true,第二張顯示 card fixed / false / true。offsetParent 在此可指出定位祖先,實際頁面還要一起檢查祖先的定位與 transform,尤其是 固定定位遇到 transform 祖先 的情況。
卡片外還有要保留的按鈕時,把裁切放進內層
若卡片有伸出邊界的選單、徽章或鍵盤焦點框,直接裁最外層可能把這些內容一併截掉。讓內層圖片區同時持有 position: relative、圓角和 overflow: hidden,把選單或按鈕留在同層的其他區塊。驗收時分別看圖片角落有沒有裁掉、選單打開後能不能顯示完整,以及 Tab 到按鈕時的焦點框是否可見。
參考資料:
CSS 圓角加了 overflow: hidden 仍裁不到子元素?檢查 absolute 定位
https://laplusda.com/posts/css-border-radius-overflow-absolute-child/