【问题标题】:How to move a div up and down infinitely in CSS?如何在 CSS 中无限上下移动 div?
【发布时间】:2020-11-13 07:04:07
【问题描述】:

我正在尝试使用底部而不是顶部来执行上下移动 div 以提供浮动/悬停效果的简单任务。

我是 CSS 和关键帧的新手!正如你可能知道的那样。但这是我尝试过的,它似乎没有做任何事情:

.Mail {
  margin-top: -77px;
  margin-left: 791px;
  animation: MoveUpDown 1s linear infinite;
}

@keyframes MoveUpDown {
  0%, 100% {
    bottom: 0;
  }
  50% {
    bottom: 20px;
  }
}
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<i class="Mail fas fa-envelope"></i>

【问题讨论】:

标签: html css css-animations


【解决方案1】:

您需要将其position 设置为absolute 以使bottom 属性 生效:

.Mail {
  margin-top: -77px;
  margin-left: 791px;
  position: absolute;
  bottom: 0;
  animation: MoveUpDown 1s linear infinite;
}

@keyframes MoveUpDown {
  50% {bottom: 20px}
}
<link href="https://use.fontawesome.com/releases/v5.0.10/css/all.css" rel="stylesheet">

<i class="Mail fas fa-envelope"></i>

【讨论】:

    【解决方案2】:

    bottomtoprightleft 需要 position 属性。默认的position 值为static,与MDN Explained here 一样无效。我强烈建议阅读bottom 指南,看看它在不同position 值下的效果!

    无论如何,您的animation 代码是正确的。但是,您需要了解 position 属性在 CSS 中的工作原理以避免类似的错误。

    P.S:首先要了解以下内容: relative absolute fixed,这是来自MDN Web Docs about Positioning的一个很好的资源

    【讨论】:

      【解决方案3】:

      对于正在寻找相同内容的其他人,这里是使用transform: translateY(); 的更简单的答案:

      .moving-div{
      margin-top:100px;
          animation-name: move;
          animation-duration: 1s;
          animation-iteration-count: infinite;
          animation-direction: alternate;
      }
      
      @keyframes move {
          0% {
              transform: translateY(25%);
          }
      
          100% {
              transform: translateY(-25%);
          }
      }
      <div class="moving-div">
      I am moving up and down
      </div>

      【讨论】:

        猜你喜欢
        • 2016-06-29
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 2013-04-01
        • 2016-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多