html - 如何在悬停时有不同的背景动画时始终显示文本?

标签 html css

我正在尝试在元素悬停时为背景颜色设置动画,但我无法做到让文本始终可见/位于顶部。似乎设置 z-index 没有做任何事情。还有什么我应该尝试做的吗?

ul li {
  background-color: #eee;
  padding: 10px;
  position: relative;
  width: 200px;
}

ul li:hover .bg:before {
  width: 50%;
}

.text {
  z-index: 999999999;
  color: #fff;
  text-shadow: 1px 1px 1px #333;
  display: inline-block;
}

.bg:before {
  content: '\A';
  position: absolute;
  background: black;
  top: 0;
  bottom: 0;
  left: 0;
  width: 2%;
  transition: all 2s;
}
<ul>
  <li>
    <div class="text">Hover over this text</div>
    <div class="bg"></div>
  </li>
</ul>

最佳答案

z-index 不会影响文本元素,因为它是静态定位的,而不是绝对定位的 bg 元素。要解决此问题,您可以将 position: relative; 添加到文本元素:

ul li {
  background-color: #eee;
  padding: 10px;
  position: relative;
  width: 200px;
}

ul li:hover .bg:before {
  width: 50%;
}

.text {
  z-index: 999999999;
  color: #fff;
  text-shadow: 1px 1px 1px #333;
  display: inline-block;
  position: relative;
}

.bg:before {
  content: '\A';
  position: absolute;
  background: black;
  top: 0;
  bottom: 0;
  left: 0;
  width: 2%;
  transition: all 2s;
}
<ul>
  <li>
    <div class="text">Hover over this text</div>
    <div class="bg"></div>
  </li>
</ul>

关于html - 如何在悬停时有不同的背景动画时始终显示文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42837900/

相关文章:

javascript - Jquery min 和 max 显示新页面

javascript - jquery 验证检查 3 个复选框的状态均已选中,然后启用按钮

javascript - 页面加载期间 IE 中没有图像的高度和宽度

css - 分析 sass 文件以查看我可以在哪里使用 compass mixins?

javascript - 如何从 Kotlin 生成 HTML 标签?

jquery - 使用 JQuery Datepicker(具有重复 ID 的元素)

html - 一旦滚动到某个点,就会粘上一个动画导航栏

html - 向上滑动内容不正常

css - 设置 SVG Material Design 图标的背景颜色

javascript - CSS全局变量随js变化