html - 为什么填充会导致动画跳跃?
问题描述
::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>
解决方案
如果您在元素上有填充,则在其中一个子元素上应用绝对位置,填充量将作为偏移量添加到该子元素。
说你有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>
推荐阅读
- android - 如何正确地将共享元素转换从 RecyclerView 映射到 ViewPager?
- python - 如何将十进制值字符串从excel转换为float
- node.js - ECONNREFUSED 127.0.0.1:3000 在 TCPConnectWrap.afterConnect [as oncomplete] 错误:'ECONNREFUSED',
- jquery - Jquery 循环遍历 .get 中的项目并使用 jquery 获取 .text()
- excel - 函数正在产生不匹配错误。不知道为什么更改变量名解决了它
- android - 2 xamarin 形式的 ScrollViews
- python - 如何使用大型数据集在python中查找和替换字符串
- php - PHP如何计算多维数组中的对象?
- github-pages - 在 github 页面上链接发布工件(私人仓库)
- c - 如何从C中的文件中读取浮点数