如何使用 CSS 設定底部邊框動畫的寬度?


在 CSS 中,我們可以使用 ‘border-bottom’ CSS 屬性來設定 HTML 元素的底部邊框。我們可以使用 animation 屬性來設定底部邊框寬度的動畫。

此外,我們需要透過更改底部邊框的寬度來定義關鍵幀以使其具有動畫效果。

語法

使用者可以遵循以下語法來設定底部邊框寬度的動畫。

selector {
   animation: mymove 5s infinite;
}
@keyframes mymove {
   50% {
      border-bottom: 25px solid black;
    }
}

在上述語法中,我們建立了 ‘mymove’ 關鍵幀,以將底部邊框的寬度從 5px 動畫到 25px。

示例 1

在下面的示例中,我們建立了包含 ‘test’ 類的 div 元素。此外,我們還對 div 元素應用了一些 CSS 來對其進行樣式設定。我們使用 ‘animation’ 屬性根據 ‘mymove’ 關鍵幀對 div 元素進行 5 秒鐘無限次動畫。

在 ‘mymove’ 關鍵幀中,我們將底部邊框的寬度更改為 0%、30%、60%、85% 和 100%。在輸出中,使用者可以看到底部邊框寬度的動畫。

<html>
<head>
   <style>
      .test {
         width: 500px;
         height: 200px;
         background-color: red;
         border: 2px solid green;
         border-bottom: 5px solid black;
         animation: mymove 5s infinite;
       }
       @keyframes mymove {
          0% { border-bottom: 5px solid black; }
          30% { border-bottom: 15px solid black; }
          60% { border-bottom: 25px solid black; }
          85% {  border-bottom: 15px solid black; }
          100% { border-bottom: 5px solid black; }
      }
   </style>
</head>
<body>
   <h2> Adding the <i> animation </i> to bottom border using CSS </h2>
   <div class = "test"> </div>
</html>

示例 2

在下面的示例中,我們建立了 <h2> 元素並在其中添加了一些文字內容。之後,我們使用 CSS 屬性來設定元素的樣式。我們還使用 ‘animation’ 屬性來設定底部邊框寬度的動畫。

在 ‘border-animation’ 關鍵幀中,我們透過保持其他邊框屬性不變來更改邊框的寬度。

<html>
<head>    
    <style>
        .test {
            width: fit-content;
            border: 1px dotted blue;
            border-bottom: 1px solid red;
            animation: border-animation 1.5s infinite ease-in-out;
            padding: 5px 10px;
            color: green;
        }

        @keyframes border-animation {
            0% { border-bottom: 1px solid red; }
            30% { border-bottom: 3px solid red; }
            50% { border-bottom: 5px solid red; }
            70% { border-bottom: 3px solid red; }
            100% { border-bottom: 1px solid red; }
        }
    </style>
</head>
<body>
    <h2> Adding the <i> animation </i> to bottom border of checkbox using CSS</h2>
    <h2 class = "test"> Welcome to the TutorialsPoint! </h2>
</html>

使用者學習瞭如何使用 CSS 設定底部邊框寬度的動畫。我們需要使用 ‘animation’ CSS 屬性併為動畫定義關鍵幀。在關鍵幀中,我們可以使用 ‘border-bottom’ 或 ‘border-bottom-width’ CSS 屬性更改底部邊框的寬度。

更新於:2023年5月17日

759 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.