首页 > 解决方案 > 为什么我的动画属性在 CSS 中不起作用

问题描述

我正在尝试使用 CSS 中的动画属性将 div 从左向右移动。但是代码不起作用。

我是 CSS 中动画属性的新手。我参考了 W3Schools 和 StackOverFlow 中的一些文章,但仍然没有成功。

#title {
  font-size: 8.5em;
  font-weight: bold;
  color: goldenrod;
  animation: move 3s ease;
  animation-direction: normal;
}

@keyframes move {
  from {
    left: 0;
  }
  to {
    left: 200px;
  }
}
<div id="title">Soy Boos</div>

Soy Boos 这个词应该从左向右移动

标签: htmlcsscss-animations

解决方案


嘿@Gan 从 w3schools 中了解了left 属性,它具有以下定义和用法


left 属性影响定位元素的水平位置。此属性对非定位元素没有影响。

• 如果位置:绝对;或位置:固定;- left 属性将元素的左边缘设置为其最近定位的祖先的左边缘左侧的一个单位。

• 如果位置:相对;- left 属性将元素的左边缘设置为其正常位置的左侧/右侧的一个单位。

• 如果位置:粘性;- 当元素在视口内时,left 属性的行为就像它的位置是相对的,而当它在视口外时它的位置是固定的。

• 如果位置:静态;- left 属性无效。


因此,您只需向元素添加position属性即可使属性起作用...#titleleft

#title{
  font-size: 8.5em;
  font-weight: bold;
  color: goldenrod;
  animation: move 3s ease; 
  animation-direction: normal;
  position:relative; /* this one */
}

@keyframes move{
  from {left:0;}
  to {left:200px;}
}
<div id="title">Soy Boos</div>


推荐阅读