在悬停时向上移动HTML元素

8 html css css-animations

每当用户将鼠标悬停在它上面时,我试图将HTML移动大约10px.我对w3schools进行了一些研究,但我找不到任何帮助我的信息.他们的大多数动画示例都使用关键帧,我很确定这不是我需要的,因为当有人在元素上盘旋时我正试图触发动画.我可能错了,这就是我在这里发帖的原因.

这是我想要移动的元素:

<div id="arrow">
  <a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>
Run Code Online (Sandbox Code Playgroud)

对于我的CSS:

#arrow {
  padding-top: 310px;
  color: #5C6B7E;
  position: relative;
  /* some kind of animation property here? */
}

#arrow:hover {
  /* new properties once user hovers */
}
Run Code Online (Sandbox Code Playgroud)

我不确定我需要添加什么来使元素生动起来,w3schools上的例子没有多大帮助.如果有人能指出我正确的方向,我将非常感激.谢谢Stack Overflow.

Man*_*mar 20

您无需为这个简单的动画使用关键帧.只是CSS过渡就足够了.

transition使用持续时间在初始状态样式规则中设置属性.

#arrow {
  position: relative;
  top: 0;
  transition: top ease 0.5s;
}
#arrow:hover {
  top: -10px;
}
Run Code Online (Sandbox Code Playgroud)
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<div id="arrow">
  <a href="#"><i class="fa fa-arrow-down fa-2x"></i></a>
</div>
Run Code Online (Sandbox Code Playgroud)


Spe*_*ric 11

margin-top如果您的元素是绝对定位的,您也可以尝试在悬停时应用负数:

div {
  padding: 1em;
  border: 1px solid #b5b5b5;
  border-radius: 10px;
  width: fit-content;
  transition: 0.5s;
}

div:hover {
  box-shadow: 0 0 3px black;
  margin-top: -10px;
}
Run Code Online (Sandbox Code Playgroud)
<br/>
<div>
  <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
</div>
Run Code Online (Sandbox Code Playgroud)


小智 8

我在尝试解决用鼠标悬停在元素上时移动元素时遇到的问题时遇到了这个问题。以上都不起作用,所以我想我应该分享我在运行的测试中提出的解决方案:

.item {
  background-color: black;
  display: flex;
  width: 100px;
  height: 40px;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white;
  transition: transform ease 300ms;
}

.item:hover {
  transform: translate(0, -10px);
}
Run Code Online (Sandbox Code Playgroud)
<div class="item">TEST</div> 
Run Code Online (Sandbox Code Playgroud)