You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS实现鼠标悬停时图片变黑并显示白色文字效果?

解决悬停时图片变黑且显示白色文字的问题

要实现你要的效果,核心是让文字叠加在图片上方,同时仅对图片应用变暗效果,避免影响文字。以下是具体实现方案:

关键思路

  1. 调整布局,让标题文字覆盖在图片区域:将父容器设为相对定位,标题设为绝对定位,确保文字悬浮在图片上方。
  2. 悬停时单独对图片应用变黑效果(不影响父容器内的文字)。
  3. 给文字和图片添加过渡动画,提升交互流畅度。

完整代码实现

CSS 代码

.post_feature_outer {
  position: relative;
  display: inline-block; /* 容器宽度适配图片 */
}

.post_feature_title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 文字居中 */
  margin: 0;
  color: rgba(255, 255, 255, 0);
  transition: color 0.3s ease;
  z-index: 1; /* 确保文字在图片上方 */
}

.post_feature_img {
  display: block;
  transition: filter 0.3s ease;
}

.post_feature_outer:hover .post_feature_title {
  color: white;
}

.post_feature_outer:hover .post_feature_img {
  filter: brightness(0); /* 图片完全变黑 */
}

/* 保留原背景样式 */
body {
  background: #222;
}

HTML 代码(无需修改结构)

<div class='post_feature_outer'>
  <h1 class="post_feature_title">VOGUE ITALIA – JUNE 2022 ISSUE</h1>
  <img class="post_feature_img" src="https://via.placeholder.com/300x200" />
</div>

方案说明

  • 布局调整:父容器的position: relative为标题的绝对定位提供参照,标题通过transform实现居中,z-index: 1保证文字始终在图片上层。
  • 图片变黑效果:仅对图片单独应用filter: brightness(0),不会影响文字的颜色显示,解决了你之前用父容器滤镜导致文字被隐藏的问题。
  • 过渡动画:给文字的color和图片的filter添加过渡,让悬停效果更自然。

替代方案(伪元素遮罩)

如果不想使用filter,可以通过父容器的伪元素实现黑色遮罩,兼容性更好:

.post_feature_outer {
  position: relative;
  display: inline-block;
}

.post_feature_title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
  color: rgba(255, 255, 255, 0);
  transition: color 0.3s ease;
  z-index: 2;
}

.post_feature_img {
  display: block;
}

.post_feature_outer::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.post_feature_outer:hover .post_feature_title {
  color: white;
}

.post_feature_outer:hover::after {
  opacity: 1;
}

body {
  background: #222;
}

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:46:30