按钮边框动画

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将探索如何使用 CSS 在按钮悬停时创建边框动画。通过使用 ::before::after 伪元素,我们可以在按钮上方和下方添加两个框,并在悬停时将它们的宽度过渡到 100%。本实验将帮助你提升 CSS 技能,并为你的网页增添交互性。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 100%。获得了学习者 100% 的好评率。

按钮边框动画

虚拟机中已经提供了 index.htmlstyle.css

要在悬停时创建边框动画,你可以使用 ::before::after 伪元素来生成两个宽度为 24px 的框,并将它们定位在按钮框的上方和下方。然后,应用 :hover 伪类,在悬停时将这些元素的 宽度 增加到 100%,并使用 transition 为过渡添加动画效果。

以下是一个示例代码片段:

<button class="animated-border-button">提交</button>
.animated-border-button {
  background-color: #263059;
  border: none;
  color: #ffffff;
  outline: none;
  padding: 12px 40px 10px;
  position: relative;
}

.animated-border-button::before,
.animated-border-button::after {
  border: 0 solid transparent;
  transition: all 0.3s;
  content: "";
  height: 0;
  position: absolute;
  width: 24px;
}

.animated-border-button::before {
  border-top: 2px solid #263059;
  right: 0;
  top: -4px;
}

.animated-border-button::after {
  border-bottom: 2px solid #263059;
  bottom: -4px;
  left: 0;
}

.animated-border-button:hover::before,
.animated-border-button:hover::after {
  width: 100%;
}

请点击右下角的“上线”以在端口 8080 上运行网络服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了按钮边框动画实验。你可以在 LabEx 中练习更多实验来提升你的技能。