You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS仅为Navbar中的SHOP元素添加动画,其余元素无动画

解决导航栏打字动画导致其他元素移动的问题

问题原因

当前带有打字动画的.name元素为inline-block类型,动画过程中宽度从0逐渐变为73px,会直接改变它在布局中占据的空间,进而挤压相邻的导航元素,导致所有元素跟着移动。

解决方案

给包含.name的<a>标签设置固定宽度和inline-block属性,让它始终占据固定的空间,内部的打字动画仅在这个固定容器内进行,不会影响外部布局。

修改后的代码

CSS 代码

* {
  margin: 0;
}

.navbar {
  font-family: monospace;
  font-size: 1.3rem;
  padding: 1%;
  background-color: rgb(235, 178, 178);
}

.navbar a {
  margin-left: 1.5%;
  text-decoration: none;
  color: black;
  padding: 0.6%;
}

/* 新增:给SHOP的容器设置固定宽度 */
.shop-link {
  display: inline-block;
  width: 73px; /* 与.name动画后的宽度一致 */
}

.navbar a:not(.name):hover {
  animation: none;
}

.searchbar {
  margin-left: 600px;
  padding: 10px;
  text-align: left;
  width: 500px;
  height: 10%;
  color: #fff;
  font-size: 17px;
  border: black;
  font-weight: 500;
  background: black;
  border-radius: 10px;
}

.navbar button {
  height: 10%;
  border-radius: 10px;
  padding: 10px;
  color: white;
  font-size: 17px;
  background: black;
  border: none;
  border-radius: 10px;
  cursor: pointer;
}

.name {
  margin-top: 2px;
  margin-bottom: 0px;
  display: inline-block;
  font-size: 1.2em;
  color: black;
  background-color: rgb(235, 178, 178);
  padding: 0px;
  letter-spacing: 1px;
  font-family: monospace;
  border-right: 5px solid;
  width: 73px;
  white-space: nowrap;
  overflow: hidden;
  animation: typing 2s steps(5), cursor 0.4s step-end infinite alternate;
}

@keyframes cursor {
  50% {
    border-color: transparent;
  }
}

@keyframes typing {
  from {
    width: 0;
  }
}

HTML 代码

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles.css" />
    <title>Hasgu</title>

    <script
      src="https://kit.fontawesome.com/e5e83f9d84.js"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <nav class="navbar">
      <!-- 新增shop-link类 -->
      <a href="#" class="shop-link"><p class="name">SHOP</p></a>
      <a href="">Home</a>
      <a href="">Products</a>
      <a href="">About</a>
      <a href="">Contact</a>
      <input type="search" class="searchbar" placeholder="Search" required />
      <button type="submit" class="fas fa-search"></button>
    </nav>
  </body>

额外说明

  • 给shop-link设置的宽度必须和.name动画完成后的宽度一致(这里是73px),才能保证布局稳定。
  • 如果后续修改了SHOP的文字内容或字体样式,需要同步调整这个固定宽度值。

内容的提问来源于stack exchange,提问作者RaGhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:02:03