萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

純 CSS3 動畫導航選單:入場動態、懸停三角指標與交錯延遲

效果特色

  • 水平選單項目依序從下往上淡入(交錯延遲)。
  • 底部中央紅線由左向右伸展(scaleX 動畫)。
  • 懸停/當前態顯示紅色三角指標,帶彈入動畫。
  • 零 JavaScript,全靠 CSS Animation + Transform。

HTML 結構

<ul class="main-menu">
  <li class="main-menu-item active"><a href="#">Home</a></li>
  <li class="main-menu-item"><a href="#">About Us</a></li>
  <li class="main-menu-item"><a href="#">Another Link</a></li>
  <li class="main-menu-item"><a href="#">And another</a></li>
  <li class="main-menu-item"><a href="#">Stuff</a></li>
  <li class="main-menu-item"><a href="#">Help</a></li>
  <li class="main-menu-item"><a href="#">Contact</a></li>
</ul>

核心 CSS 解析

1. 容器與基線

.main-menu {
  display: flex;
  justify-content: center;
  gap: 0; /* 項目間距由 padding 控制 */
  list-style: none;
  margin: 2em auto 0;
  width: 960px;
  position: relative;
}

2. 底部紅線動畫(::after 偽元素)

.main-menu::after {
  content: '';
  position: absolute;
  bottom: 0; left: 0; right: 0;
  margin: auto;
  width: 70%; height: 2px;
  background: #9b1c27;
  transform: scaleX(0);
  opacity: 0;
  animation: menuLine 1s ease forwards;
}
@keyframes menuLine {
  to { transform: scaleX(1); opacity: 1; }
}

3. 選單項目入場動畫

.main-menu-item a {
  display: block;
  padding: 1em;
  color: #555;
  text-decoration: none;
  opacity: 0;
  transform: translateY(40%);
  animation: menuItem 0.8s ease forwards;
  transition: color 0.2s ease;
}
@keyframes menuItem {
  to { opacity: 1; transform: translateY(0); }
}

/* 交錯延遲:從中間向兩側擴散 */
.main-menu-item:nth-child(4) a { animation-delay: 0.4s; }  /* 中間 */
.main-menu-item:nth-child(3) a,
.main-menu-item:nth-child(5) a { animation-delay: 0.5s; }
.main-menu-item:nth-child(2) a,
.main-menu-item:nth-child(6) a { animation-delay: 0.6s; }
.main-menu-item:nth-child(1) a,
.main-menu-item:nth-child(7) a { animation-delay: 0.7s; }

4. 懸停/當前態三角指標

.main-menu-item:hover a::after,
.main-menu-item.active::after {
  content: '';
  position: absolute;
  bottom: 0; left: 0; right: 0;
  margin: auto;
  width: 0; height: 0;
  border: 0.5em solid transparent;
  border-bottom-color: #9b1c27;
  opacity: 0;
  transform: translateY(0.05em);
  animation: menuItem 0.8s 1.2s ease forwards; /* 延遲 1.2s 彈入 */
}

.main-menu-item:hover a,
.main-menu-item.active a { color: #9b1c27; }

關鍵技術點總結

技術用途關鍵屬性
Flexbox水平置中、等寬/自適應分佈display:flex; justify-content:center
偽元素 ::after裝飾性紅線、三角指標content:''; position:absolute
CSS Animation入場、伸展、彈入@keyframes, animation, forwards
Transform位移、縮放、旋轉(GPU 加速)translateY, scaleX
nth-child交錯延遲計算animation-delay
Border 三角形零寬高邊框組合成三角border: solid transparent; border-bottom-color: ...

擴展與客製化

  1. 響應式:@media (max-width: 768px) { .main-menu { flex-wrap: wrap; width: auto; padding: 1em; } }
  2. 主題色變數:提取 --menu-color: #9b1c27; 至 :root,支援深色模式切換。
  3. 無障礙:aria-current="page" 標記當前頁,prefers-reduced-motion 媒體查詢停用動畫。
  4. Web Component 封裝:<animated-menu items="[...]"> 內部 Shadow DOM 隔離樣式。
copyright © 萬盛學電腦網 all rights reserved