CSS 动画使 <h1> 元素在我将鼠标悬停在其上时平移 3px

CSS animation to make an <h1> element translate 3px higher when I hover over it

我正在尝试创建一个带有元素的按钮。我试图给这个按钮一个小的行为,当我将鼠标悬停在它上面时让它上升 3px。

我试过将 transform:translateY(-3px); 作为@keyframes 动画(在代码片段中就是这样),我也试过简单地将 transform:translateY(-3px); 放在 header-main:hover 选择器下。这两种方式似乎都使按钮远离了它应该是的样子。它似乎改为右下角。

请记住,我对编码很陌生,因为这是我第 2 个月的编码,

谢谢!

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

/*Tag Selectors*/
body {
  font-family: 'Lato', sans-serif;
  height: 100%;
  width: 100%;
}


header {
  background-position: top;
  background-size: cover;
  position: relative;
  display: inline-block;
  height: 95vh;
  margin: 20px;
  width: 100%;
  background-image: linear-gradient(to bottom right, white, #00000045);
}

/*Class Selectors*/
.header-main {
  border-radius: 500px;
  background-color: black;
  color: white;
  display: inline-block;
  font-weight: 700;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  letter-spacing: 3px;
  padding: 10px 30px;
}

.header-main:hover {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  animation: jumpUp 0.2s ease-out;
}

@keyframes jumpUp {
50% {
  transform: translateY(-3px);
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Test for btn</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body>
    <header>

        <h1 class="header-main">Start free trial</h1>
      
        </header>






  </body>
</html>

translateY 正在重做整个转换(删除 `translateX 和原来的 translateY)。相反,使用原始翻译并从 y:

中减去 3px

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

/*Tag Selectors*/
body {
  font-family: 'Lato', sans-serif;
  height: 100%;
  width: 100%;
}


header {
  background-position: top;
  background-size: cover;
  position: relative;
  display: inline-block;
  height: 95vh;
  margin: 20px;
  width: 100%;
  background-image: linear-gradient(to bottom right, white, #00000045);
}

/*Class Selectors*/
.header-main {
  border-radius: 500px;
  background-color: black;
  color: white;
  display: inline-block;
  font-weight: 700;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  letter-spacing: 3px;
  padding: 10px 30px;
}

.header-main:hover {
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  animation: jumpUp 0.2s ease-out;
}

@keyframes jumpUp {
50% {
  transform: translate(-50%, calc(-50% - 3px));
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Test for btn</title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body>
    <header>

        <h1 class="header-main">Start free trial</h1>
      
        </header>






  </body>
</html>

所以里面 keyframes:

transform: translate(-50%, calc(-50% - 3px));