CSS 圓角 (border-radius)

border-radius 屬性用來設定元素的圓角效果,讓方形的邊角變成圓弧。

基本用法

.rounded {
  border-radius: 10px;    /* 四個角相同 */
}

各角設定

可以對每個角設定不同的圓角大小:

/* 四個值:左上 右上 右下 左下(順時針) */
.different {
  border-radius: 10px 20px 30px 40px;
}

/* 兩個值:左上和右下 / 右上和左下 */
.two {
  border-radius: 10px 20px;
}

/* 三個值:左上 / 右上和左下 / 右下 */
.three {
  border-radius: 10px 20px 30px;
}

個別角落屬性

.custom {
  border-top-left-radius: 10px;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 30px;
  border-bottom-left-radius: 40px;
}

橢圓形圓角

/ 分隔水平和垂直方向的半徑,可以製作橢圓形的圓角:

.ellipse {
  border-radius: 50px / 25px;    /* 水平 50px,垂直 25px */
}

/* 各角不同的橢圓 */
.fancy {
  border-radius: 10px 20px 30px 40px / 5px 10px 15px 20px;
}

圓形

border-radius 設為 50% 可以把正方形變成圓形:

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

對於非正方形元素,50% 會變成橢圓形。

膠囊形狀

設定一個很大的值,可以讓長方形變成膠囊形狀:

.pill {
  padding: 10px 30px;
  border-radius: 9999px;    /* 或 999px、100px 等足夠大的值 */
}

常用數值

效果數值
微圓角4px
小圓角8px
中圓角12px16px
大圓角24px32px
圓形/膠囊50%9999px

實用範例

圓角卡片

.card {
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

圓角按鈕

.btn {
  padding: 10px 24px;
  border-radius: 8px;
  background: #007bff;
  color: white;
}

/* 膠囊按鈕 */
.btn-pill {
  padding: 10px 24px;
  border-radius: 9999px;
}

頭像

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

只有上方圓角

.card-header {
  border-radius: 12px 12px 0 0;
}

只有下方圓角

.card-footer {
  border-radius: 0 0 12px 12px;
}

對話氣泡

.bubble {
  background: #007bff;
  color: white;
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
}

.bubble-right {
  border-radius: 18px 18px 4px 18px;
}

輸入框

input {
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

input:focus {
  border-color: #007bff;
  outline: none;
}

與其他屬性搭配

搭配 overflow

當內容超出圓角區域時,需要加上 overflow: hidden

.card {
  border-radius: 12px;
  overflow: hidden;    /* 確保內容不會超出圓角 */
}

搭配 border

.box {
  border: 2px solid #007bff;
  border-radius: 8px;
}

搭配 box-shadow

.card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

注意事項

  • border-radius 會影響元素的點擊區域,圓角外的部分無法點擊
  • 對於圖片,可能需要加上 overflow: hidden 來裁切超出的部分
  • 過大的圓角值在某些瀏覽器中可能有微小的渲染差異