首页 > 解决方案 > 为什么填充会导致动画跳跃?

问题描述

::before当我将顶部和底部填充应用于其父元素时,为什么伪元素会在高度过渡期间跳跃?

a {
  font-size: 2em;
  font-family: sans-serif;
  text-transform: uppercase;
  color: #fff;
  text-decoration: none;
  position: relative;
  /* Removing this padding resolves the animation issue, but why? */
  padding: 1em;
}

a::before {
  content: "";
  width: 0.06em;
  height: 0%;
  position: absolute;
  background: #fff;
  left: 0;
  transition: height 0.25s linear;
}

a:hover::before {
  height: 100%;
  bottom: 0;
}

.container {
  background: #3a3a3a;
  height: 100%;
  display: flex;
  padding-top: 1em;
  justify-content: center;
  align-items: flex-start;
}

body,
html {
  height: 100%;
  margin: 0;
}
<div class="container">
  <a href="#">Hover Me</a>
</div>

标签: htmlcss

解决方案


如果您在元素上有填充,则在其中一个子元素上应用绝对位置,填充量将作为偏移量添加到该子元素。

说你有padding-top:10px;,它会变成top:10px,我认为有些浏览器确实休息了这个。

演示

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

.test {
  width: 100px;
  height: 100px;
  padding-top: 15px;
  border: 5px solid red;
}

.test>div {
  height: 50px;
  width: 50px;
  border: 5px solid red;
}

.test:hover>div {
  position: absolute;
  /* uncomment this line to see it */
  /* top: 0; */
}
<div class="test">
  <div></div>
</div>


现在来解决你的问题。

a {
  font-size: 2em;
  font-family: sans-serif;
  text-transform: uppercase;
  color: #fff;
  text-decoration: none;
  position: relative;
  padding: 1em;
}

a::before {
  content: "";
  width: 0.06em;
  height: 0%;
  position: absolute;
  background: #fff;
  left: 0;
  /* rest the top here */
  top: 0;
  transition: height 0.25s linear;
}

a:hover::before {
  height: 100%;
  bottom: 0;
  /* unsetting the top because top:0 bottom:0; is full heiht which will prevent the animation the way you want it*/
  /* unsetting the top and not the bottom so it goes upward */
  top: unset;
}

.container {
  background: #3a3a3a;
  height: 100%;
  display: flex;
  padding-top: 1em;
  justify-content: center;
  align-items: flex-start;
}

body,
html {
  height: 100%;
  margin: 0;
}
<div class="container">
  <a href="#">Hover Me</a>
</div>


推荐阅读