首頁  >  文章  >  web前端  >  創建帶有動畫漸變邊框的精美卡片

創建帶有動畫漸變邊框的精美卡片

Patricia Arquette
Patricia Arquette原創
2024-10-21 14:42:02891瀏覽

在本教學中,我將引導您使用 CSS 自訂屬性來建立動畫漸層邊框效果,這可以為您的 UI 元件添加動態且引人注目的外觀。最後,您將擁有一張帶有動畫漸變邊框的簡單卡片,使用 css 自訂 @property。

如果您不熟悉 css 自訂@property,請先閱讀此部落格。

基本卡片結構

我們將在本教程中使用 React,基本卡片將如下所示

import "./styles.css";

const CardAnimatedBorder = () => {
  return (
    <div className="container">
      <div className="card">This is a card with animated gradient border</div>
    </div>
  );
};

export default CardAnimatedBorder;

為卡片添加基本樣式

.container {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card {
  margin: 0 auto;
  padding: 2em;
  width: 300px;
  background: #1c1f2b;
  text-align: center;
  border-radius: 10px;
  color: #ffffff;
  position: relative;
}

建立一個簡單的邊框

在創建漸變動畫邊框之前,讓我們看看如何創建簡單的邊框。我們不會使用 css border 屬性,而是使用卡片的偽元素 ::before 和 ::after。這裡的另一個重要屬性是 inset,它允許我們將偽元素放置在卡片內。 z-index 將為 -1,因為我們希望邊框位於卡片內容下方。

.card::after,
.card::before {
  content: "";
  position: absolute;
  background: red;
  inset: -4px;
  z-index: -1;
  border-radius: 10px;
}

我們的卡片現在看起來像這樣

Create fancy card with animated gradient border

新增自訂屬性--angle

我們將新增一個自訂屬性來追蹤漸層的角度。我們將使用圓錐梯度。
新增像這樣的自訂屬性

@property --angle {
  syntax: "<angle>";
  initial-value: 0deg;
  inherits: false;
}

並對 css 進行以下更改

  • 用背景影像取代背景以顯示漸層。
  • 為自訂屬性角度新增動畫旋轉。
  • 二次曲線梯度的第一個參數是角度,我們將更改它以便進行動畫處理。
  • 添加模糊和不透明度以獲得發光效果。

你的CSS應該是這樣的

.container {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.card {
  margin: 0 auto;
  padding: 2em;
  width: 300px;
  background: #1c1f2b;
  text-align: center;
  border-radius: 10px;
  color: #ffffff;
  position: relative;
}

@property --angle {
  syntax: "<angle>";
  initial-value: 0deg;
  inherits: false;
}
.card::after,
.card::before {
  content: "";
  position: absolute;
  background-image: conic-gradient(
    from var(--angle),
    transparent 70%,
    blue,
    red
  );
  inset: -4px;
  z-index: -1;
  border-radius: 10px;
  animation: 2s spin linear infinite;
}

.card::before {
  filter: blur(1rem);
  opacity: 0.7;
}

@keyframes spin {
  from {
    --angle: 0deg;
  }
  to {
    --angle: 360deg;
  }
}

最後我們有了一張有動畫漸層邊框的卡片。

示範

點這裡

閱讀更多

  • MDN 文件@property

原帖

以上是創建帶有動畫漸變邊框的精美卡片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn