如何在 CSS 中的图像悬停效果上创建图像叠加

问题描述 投票:0回答:2

我想创建类似的效果,如下图所示。它应该支持不同尺寸的图像和图像叠加。

image hover effect

我已经成功创建了上述效果,但是当容器与图像尺寸不同时,图像叠加层没有覆盖容器。

.container {
  display: inline-block;
  position: relative;
  width: 150px;
  height: 150px;
}

.image {
  display: block;
  width: 100%;
  height: auto;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
}

.container:hover .overlay {
  opacity: 1;
}

.overlay img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <img src="https://cozytux.com/wp-content/uploads/2014/07/placehold.it-500x750.gif" alt="Avatar" class="image">
  <div class="overlay">
    <img src="https://i.pinimg.com/originals/03/8b/b8/038bb804bd1611a46e4b1bafc4c6bca3.jpg">
  </div>
</div>

<div class="container">
  <img src="https://www.kingsporttn.gov/wp-content/uploads/2021/09/500x500.png" alt="Avatar" class="image">
  <div class="overlay">
    <img src="https://driverslicenserestorers.com/wp-content/uploads/placeholder-500x500.gif">
  </div>
</div>

html css image css-transitions
2个回答
0
投票

如果两个图像具有相同的尺寸,并且尺寸已知,则可以使用单个 img 标签和 box-sizing 属性。此选项允许您在标签中使用这两个图像。一个首先显示在 src 属性中,另一个作为背景。 在显示想法的片段下方,将鼠标悬停在图像上

img {
  box-sizing:border-box;
  width:500px;
  height:280px;
  background:url(https://picsum.photos/id/30/500/280);
  transition:0.25s
}
img:hover {
  padding:140px 250px;/* all paddings equals the size of the image itself */
}
<img src="https://picsum.photos/id/63/500/280">

您甚至可以添加过渡并使用填充值来决定从哪一侧隐藏/显示另一张图像


0
投票
.container img {
  height: 100%;
  object-fit: cover;
}

您需要适合图像。我建议对两个图像使用相同的尺寸。

© www.soinside.com 2019 - 2024. All rights reserved.