跳到主要內容
Jun DEV
回到 Labs

CSS STUDY / 002

The Shape Card

用一條 CSS 路徑,在卡片上留出剛剛好的圓弧。改變寬度,凹口依然與頭像對齊。

CSSclip-pathshape()

LIVE DEMO

寬度在變,圓弧始終置中。

隨容器置中
420px

切換 shape() 與 path(),再拖動滑桿比較:shape() 的凹口保持置中,path() 的凹口停在原本的位置。小螢幕上,卡片會自動縮小以符合容器。

此瀏覽器尚未支援 shape(),目前以 CSS mask 顯示相同的凹口。

靈感來自 @sanyampunia 的 CSS tip,以 Jun 的個人卡片重新演繹。

查看原作

BUILD WITH CSS

讓形狀跟著容器走。

shape() 可以混用百分比、px 與 calc()。50% 找到卡片中心,62px 定義凹口半徑;卡片縮放時,不必重新計算路徑。

01

把頭像放在裁切區域外

卡片與頭像放在同一個相對定位容器中,頭像是卡片的兄弟元素。如此 clip-path 只裁切卡片,不會切掉頭像。

<div class="profile">
  <div class="card">
    <h2>Jun.</h2>
    <p>Frontend developer</p>
  </div>
  <img class="avatar" src="/avatar.webp" alt="Jun" />
</div>
02

沿著上緣,畫出半圓凹口

從左上角出發,畫到中心左側,再用逆時針的 arc 畫到中心右側,最後沿著其餘三邊封閉路徑。104px 的頭像搭配 124px 的凹口,留出 10px 的間距。

.profile {
  position: relative;
  width: 100%;
  max-width: 420px;
  margin-top: 52px;
}

.avatar {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 104px;
  height: 104px;
  border-radius: 50%;
  object-fit: cover;
}

.card {
  padding: 80px 24px 28px;
  background: #fbfaf6;
  color: #20352c;
  text-align: center;
  border-radius: 24px;
  clip-path: shape(
    from 0 0,
    hline to calc(50% - 62px),
    arc to calc(50% + 62px) 0 of 62px ccw,
    hline to 100%,
    vline to 100%,
    hline to 0,
    close
  );
}
03

替舊瀏覽器保留相同外觀

預設以徑向漸層 mask 挖出凹口。支援 shape() 時,再以 @supports 切換為 clip-path。Vue 只更新卡片寬度,形狀由 CSS 處理。

/* Keep the layout styles above, then use progressive enhancement. */
.card {
  clip-path: none;
  mask-image: radial-gradient(
    circle at 50% 0,
    transparent 62px,
    #000 62.5px
  );
}

@supports (clip-path: shape(from 0 0, hline to 100%, vline to 100%, close)) {
  .card {
    mask-image: none;
    clip-path: shape(
      from 0 0,
      hline to calc(50% - 62px),
      arc to calc(50% + 62px) 0 of 62px ccw,
      hline to 100%,
      vline to 100%,
      hline to 0,
      close
    );
  }
}
閱讀 MDN 文件