CSS3 border-radius 讓圓角邊框無需圖片、無需複雜結構即可實現。本文涵蓋標準語法、瀏覽器前綴、IE 兼容方案(HTC/PIE)、響應式圓角與進階造型技巧。
.box {
/* 標準語法(現代瀏覽器無需前綴) */
border-radius: 12px;
/* 歷史前綴(現代構建工具自動添加) */
-webkit-border-radius: 12px; /* Safari 4-、Chrome 10-、iOS 4- */
-moz-border-radius: 12px; /* Firefox 4- */
-ms-border-radius: 12px; /* IE 預覽版 */
-o-border-radius: 12px; /* Opera 10.5- */
}
/* 四個角不同半徑:左上、右上、右下、左下 */
border-radius: 20px 10px 30px 5px;
/* 水平/垂直半徑分離:橢圓角 */
border-radius: 50px / 20px; /* 水平半徑 50px,垂直半徑 20px */
/* 完整寫法:8 個值 */
border-radius:
20px 10px 30px 5px / /* 水平半徑 */
10px 20px 5px 30px; /* 垂直半徑 */
.rounded {
border-radius: 10px;
behavior: url(/js/PIE.htc); /* 相對 HTML 文件路徑 */
position: relative; /* 必須:觸發 hasLayout */
/* PIE 支持:border-radius, box-shadow, linear-gradient, multiple backgrounds */
}
下載:CSS3 PIE 官網
.rounded {
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
behavior: url(/js/border-radius.htc); /* 僅實現 border-radius */
}
不推薦,代碼極其冗長,維護困難。
<!DOCTYPE html>
<html>
<head>
<style>
.box1 {
width: 500px; height: 50px;
margin: 20px auto;
padding: 20px;
border: 1px solid #d7d7d7;
background: #f0f0f0;
border-radius: 10px;
}
.box2 {
width: 400px; height: 200px;
margin: 20px auto;
padding: 30px;
color: #fff; font-weight: bold;
border: 10px solid #35b70e;
background: url(ashera.jpg) no-repeat top left;
border-radius: 30px;
behavior: url(border-radius.htc);
position: relative;
}
.box3 {
width: 200px; height: 30px;
padding: 20px;
position: absolute;
top: 5px; left: 5px;
background: #ddd;
border-radius: 15px;
behavior: url(border-radius.htc);
}
.rel { position: relative; zoom: 1; margin: 50px 0 0 33px; padding: 25px; }
</style>
</head>
<body>
<div class="rel">
<div class="box1">標準圓角矩形</div>
<div class="box2">帶背景圖的大圓角</div>
<div class="box3">絕對定位圓角</div>
</div>
</body>
</html>
| 形狀 | 代碼 | 原理 |
|---|---|---|
| 圓形 | border-radius: 50%; width: 100px; height: 100px; |
半徑 = 寬/高一半 |
| 膠囊/標籤 | border-radius: 999px; / border-radius: 50px; |
半徑足夠大自動變半圓 |
| 單側圓角 | border-top-left-radius: 20px; |
單獨控制一角 |
| 葉子形 | border-radius: 50% 0 50% 0; |
對角圓角 |
| 對話框尖角 | ::after { border: 10px solid transparent; border-top-color: #fff; } |
偽元素三角形 + 圓角容器 |
border-radius,構建工具(PostCSS/Autoprefixer)自動處理前綴--radius-sm: 4px; --radius-md: 8px; --radius-lg: 16px; --radius-full: 999px;box-shadow 實現立體感:box-shadow: 0 4px 12px rgba(0,0,0,0.1);border-radius: clamp(8px, 2vw, 24px);will-change: transform 提升合成層border-radius(觸發重排),改用 transform: scale + clip-pathborder-radius 觸發層疊上下文,注意 z-index 交互