使用HTML和CSS建立字母間距動畫效果


在這篇文章中,我們將使用HTML和CSS建立一個字母間距動畫效果。為此,我們將用到CSS的`letter-spacing`屬性和`@keyframes`規則。

CSS Letter-spacing 屬性

CSS中的`letter-spacing`屬性用於設定文字字元之間的水平間距。

  • 如果為該屬性賦予正值,字元間距將變大。

  • 如果為該屬性賦予負值,字元間距將變小。

語法

以下是CSS `letter-spacing`屬性的語法:

letter-spacing: value;

CSS @keyframes規則

在CSS中,`@keyframes`規則可用於透過定義關鍵幀的樣式來控制CSS動畫序列中的各個步驟。樣式更改將以百分比或使用關鍵字“from”和“to”(分別相當於0%和100%)的方式發生。0%表示動畫的開始,100%表示動畫的結束。

語法

以下是CSS `@keyframes`規則的語法:

@keyframes slidein {
   from {
      transform: translateX(0%);
   }

   to {
      transform: translateX(100%);
   }
}

以下是使用HTML和CSS建立字母間距動畫效果的步驟。

  • 步驟1 - 新增以下HTML程式碼。

在body部分,我們使用段落<p>標籤建立了兩段簡單的文字。

<body>
   <p class="animated-text1">TUTORIALSPOINT</p>
   <p class="animated-text2">Simply Easy Learning...</p>
</body>
  • 步驟2 - 包含以下CSS程式碼。

為了為以上兩段文字建立字母間距動畫,我們使用了CSS的`letter-spacing`屬性和CSS的`@keyframes`規則。

<style>
body{
 background: lightblue;
}
/* CSS for the text */
.animated-text1 {
   font-size: 50px;
   font-weight: bold;
   color: whitesmoke;
   animation: letter-spacing-animation 1s infinite alternate;
   text-align: center;
}
.animated-text2 {
   font-size: 25px;
   color: whitesmoke;
   animation: letter-spacing-animation 1s infinite alternate;
   text-align: center;
}
/* CSS animation keyframes */
@keyframes letter-spacing-animation {
   0% {
      letter-spacing: 0px;
   }
   50%{
      letter-spacing: 10px;
   }
   100% {
      letter-spacing: 20px;
   }
}
</style>

完整示例

現在,將以上兩個HTML和CSS程式碼塊組合如下:

<!DOCTYPE html>
<html>
<head>
   <title>Letter-Spacing Animation Effect</title>
   <style>
      body {
         background: lightblue;
      }
      /* CSS for the text */
      .animated-text1 {
         font-size: 50px;
         font-weight: bold;
         color: whitesmoke;
         animation: letter-spacing-animation 1s infinite alternate;
         text-align: center;
      }
      .animated-text2 {
         font-size: 25px;
         color: whitesmoke;
         animation: letter-spacing-animation 1s infinite alternate;
         text-align: center;
      }
      /* CSS animation keyframes */
      @keyframes letter-spacing-animation {
         0% {
            letter-spacing: 0px;
         }
         50% {
            letter-spacing: 10px;
         }
         100% {
            letter-spacing: 20px;
         }
      }
   </style>
</head>
<body>
   <p class="animated-text1">TUTORIALSPOINT</p>
   <p class="animated-text2">Simply Easy Learning...</p>
</body>
</html>

更新於:2023年8月29日

499 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告