【问题标题】:Can't make CSS Animations work with @keyframes and position relative/absolute无法使 CSS 动画与 @keyframes 和相对/绝对位置一起使用
【发布时间】:2021-12-05 10:12:59
【问题描述】:

我正在尝试使用关键帧练习简单的 CSS 动画。 我正在尝试将正方形从左向右移动,但是,这似乎不适用于相对/绝对位置。我在进行转换时工作: translateX(...) 或类似的东西,但不是使用上述方法。任何想法为什么?

CSS 代码:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: rgb(70, 70, 162);
}

.box1 {
  height: 600px;
  width: 80%;
  background-color: white;
  margin: 50px auto;
  border: 5px solid black;
  position: relative;
}

.square1 {
  height: 100px;
  width: 100px;
  background-color: red;

  position: absolute;
  top: 0px;
  left: 0px;

  animation-name: left-right;
  animation-duration: 3s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes left-right {
  0% {
    top: 0px;
    left: 0px;
  }

  100% {
    top: 0px;
    right: 0px;
  }
}

【问题讨论】:

    标签: css-animations css-position


    【解决方案1】:

    所以,在关键帧中,您正确

    100% {
    top: 0px;
    right: 500px;}
    

    需要向左

    100% {
    top: 0px;
    left: 500px;}
    

    完整代码:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      background-color: rgb(70, 70, 162);
    }
    
    .box1 {
      height: 600px;
      width: 80%;
      background-color: white;
      margin: 50px auto;
      border: 5px solid black;
      position: reletive;
    }
    
    .square1 {
      height: 100px;
      width: 100px;
      background-color: red;
      position: absolute;
      top: 0px;
      left: 0px;
      animation-name: left-right;
      animation-duration: 3s;
      animation-timing-function: ease-in-out;
      animation-iteration-count: infinite;
      animation-direction: alternate;
    }
    
    @keyframes left-right {
      0% {
        top: 0px;
        left: 0px;
      }
    
      100% {
        top: 0px;
        left: 500px;
        /*here*/
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 1970-01-01
      • 2015-08-15
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多