如何用动画改变元素CSS位置

Moh*_*val 6 html css user-interface

我想将HTML元素位置从静态更改为固定在前50%并保留50%的浏览器窗口,但代码只会导致背景颜色变化!

div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: static;
    top: auto;
    left: auto;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
        position: static;
        top: auto;
        left: auto;
    }
    to {
      background-color: yellow;
      position: fixed;
      top: 50%;
      left: 50%;
     }
}
Run Code Online (Sandbox Code Playgroud)

Van*_*Tzo 6

简短回答:You can't animate position.

position: fixed尝试通过 javascript 添加类fixed或其他内容,而不是通过关键帧应用 。

示例: https: //jsfiddle.net/6Ldqhoce/

您可以选择移动元素,transform: translate但它不会被修复。

  • 我之前还没有真正尝试过在浏览器维度上使用它,但我想这可能会起作用`transform:translate(50vw, 50vh)` (3认同)

Moh*_*val 2

我通过“Vangel Tzo”帮助找到了答案:

div {
    width: 100px;
    height: 100px;
    background-color: red;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    from {
        background-color: red;
    }
    to {
      background-color: yellow;
      transform: translate(50vw, 50vh);
     }
}
Run Code Online (Sandbox Code Playgroud)