css - 悬停时从底部到顶部更改背景

标签 css background css-transitions

如何使用持续时间为 0.3 秒的从底部到顶部的过渡来更改 a:hover 上的背景颜色?

<ul>
  <li><a></a></li>
  <li><a></a></li>
  <li><a></a></li>
</ul>

这可能吗?

谢谢

最佳答案

无法(通常)在 CSS 中应用过渡方向。但是,我们可以通过使用伪元素(或其他方法,例如 this example 如何使用渐变)解决该限制。

通过使用初始可见 高度为 0 的伪元素,我们可以在悬停链接时将高度从所需方向转换到所需方向。出于性能原因,最好使用 transform: scale,这意味着我们需要将 transform-origin 设置为 bottom center 在这种情况下确保它从下到上。

这种方法可能是最通用的,适用于非纯色背景等,但确实需要伪元素或子元素。

该方法的 CSS 是:

li {
    background: red;
}
a {
    position: relative;
    z-index: 1;
}
a::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transform: scaleY(0);
    transform-origin: bottom center;
    background: blue;
    z-index: -1;
    transition: transform 0.3s;
}
a:hover::after {
    transform: scaleY(1);
}

Demo

关于css - 悬停时从底部到顶部更改背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659605/

相关文章:

jquery - 将动画添加到背景图像更改

css - 使用平板电脑的导航下拉菜单

javascript - 动态创建的文本字段的不同行为

jquery - 所选元素未显示在 jquery 移动选择中 - nativedroid

javascript - 多张图像上的 CSS 过渡

css - 标题转换

css - React css 转换不能正常工作

javascript - 使用 AngularJS 为每个页面添加导航和页脚

iphone - 让 iOS 应用程序在前台运行

android - 如何在代码中为图像按钮设置透明背景?