圖片圓角是現代 Web 設計的基礎需求。本文對比多種實現方案,從最簡單的 border-radius 到複雜異形裁剪,幫你選擇最適合項目的技術路線。
<img src="photo.jpg" alt="風景照" class="rounded-img">
.rounded-img {
border-radius: 12px; /* 統一圓角 */
/* border-radius: 50%; */ /* 圓形 (需正方形圖片) */
/* border-radius: 20px 0 20px 0; */ /* 異形圓角:左上、右上、右下、左下 */
width: 300px;
height: 200px;
object-fit: cover; /* 保持比例填充,避免變形 */
}
優點:語義化、無額外 DOM、動畫性能好、支持過渡動畫。
缺點:矩形圖片強制圓角會裁剪內容;極舊瀏覽器 (IE8-) 不支持。
<div class="img-container" style="background-image: url(photo.jpg);"></div>
.img-container {
width: 300px;
height: 200px;
border-radius: 12px;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
適用場景:裝飾性圖片、需要疊加遮罩/漸變、配合 background-blend-mode 混合模式。
缺點:非內容圖片 (SEO/無障礙弱)、無法直接右鍵保存、打印樣式需特殊處理。
原文展示的「四角分別定位背景圖片」技巧,本質是用多個 <b> 元素拼接圓角邊框圖片。**現代項目不推薦**,純屬歷史遺留方案 (IE6 時代無 border-radius 時的變通)。
<img src="photo.jpg" class="clip-shape">
.clip-shape {
width: 300px;
height: 300px;
object-fit: cover;
}
/* 圓形 */
.clip-circle { clip-path: circle(50% at center); }
/* 橢圓 */
.clip-ellipse { clip-path: ellipse(50% 40% at center); }
/* 多邊形:五邊形 */
.clip-polygon { clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); }
/* 自定義 SVG 路徑 (最靈活) */
.clip-svg { clip-path: url(#custom-shape); }
<svg width="0" height="0">
<defs>
<clipPath id="custom-shape" clipPathUnits="objectBoundingBox">
<path d="M0.5,0 L1,0.38 L0.82,1 L0.18,1 L0,0.38 Z"/>
</clipPath>
</defs>
</svg>
.mask-fade {
-webkit-mask-image: linear-gradient(to bottom, black 70%, transparent);
mask-image: linear-gradient(to bottom, black 70%, transparent);
/* 或使用 SVG 遮罩 */
-webkit-mask-image: url("mask.svg");
mask-image: url("mask.svg");
}
| 方案 | 適用場景 | 瀏覽器支持 | 性能 | SEO/無障礙 | 推薦度 |
|---|---|---|---|---|---|
| border-radius (img) | 內容圖片圓角、圓形頭像 | IE9+ 全支持 | 極佳 (GPU 加速) | 優 (img 標籤) | ⭐⭐⭐⭐⭐ 首選 |
| border-radius (bg) | 裝飾圖、Hero 區、卡片背景 | IE9+ 全支持 | 極佳 | 弱 (需 ARIA 補充) | ⭐⭐⭐⭐ 裝飾首選 |
| clip-path | 非矩形裁剪、多邊形、動畫變形 | Chrome 24+, FF 3.5+, Safari 7+, Edge 79+ | 良好 (GPU) | 優 (img) | ⭐⭐⭐⭐ 異形首選 |
| mask-image | 漸變消失、複雜遮罩、SVG 遮罩 | Chrome 4+, FF 53+, Safari 4+, Edge 79+ | 良好 | 優 (img) | ⭐⭐⭐⭐ 進階首選 |
| 偽元素拼圖 (舊法) | 極舊項目維護 (IE6-8) | 全瀏覽器 | 差 (多 DOM、重繪) | 差 | ⭐ 僅維舊項目 |
.img-wrapper {
position: relative;
width: 100%;
padding-top: 66.67%; /* 3:2 比例 = 2/3 = 66.67% */
border-radius: 12px;
overflow: hidden; /* 關鍵:裁剪超出圓角的圖片部分 */
}
.img-wrapper img {
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
object-fit: cover;
}
.avatar {
width: 80px; height: 80px;
border-radius: 50%;
object-fit: cover;
transition: border-radius 0.3s ease, transform 0.3s ease;
}
.avatar:hover {
border-radius: 12px; /* 圓形變圓角矩形 */
transform: scale(1.1);
}