首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css两张图片重叠互换

发布于 2024-11-11 19:15:18
0
16

今天我们来讲一个CSS技巧,就是两张图片重叠互换的效果。这个效果可以用于轮播图切换或者图片展示中,给网页增添了一些动态感。 首先,我们需要两张图片,并将它们放置在同一个容器中。 接着,在CSS...

今天我们来讲一个CSS技巧,就是两张图片重叠互换的效果。这个效果可以用于轮播图切换或者图片展示中,给网页增添了一些动态感。
首先,我们需要两张图片,并将它们放置在同一个容器中。

<div class="image-container">
  <img class="img1" src="image1.jpg">
  <img class="img2" src="image2.jpg">
</div> 

接着,在CSS中设置容器的宽度和高度,以及两张图片的定位和z-index值。
.image-container {
  position: relative;
  width: 500px;
  height: 300px;
}
.img1 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
.img2 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
} 

此时,我们会看到两张图片叠在了一起,但是只有第二张图片是可见的。因为第二张图片的z-index值设置为2,所以它在第一张图片上面。
接下来,我们需要为这个容器添加一个:hover伪类,使鼠标移入容器时两张图片交换位置。
.image-container:hover .img1 {
  z-index: 2;
}
.image-container:hover .img2 {
  z-index: 1;
} 

代码解释很简单,当容器被hover到时,第一张图片的z-index变成2,第二张图片的z-index变成1。这样,第一张图片就显示在了上层,第二张图片就隐藏在了下层。
最后,我们来看一下完整的代码和效果:
<div class="image-container">
  <img class="img1" src="image1.jpg">
  <img class="img2" src="image2.jpg">
</div>
<br>
<style>
.image-container {
  position: relative;
  width: 500px;
  height: 300px;
}
.img1 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
.img2 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
.image-container:hover .img1 {
  z-index: 2;
}
.image-container:hover .img2 {
  z-index: 1;
}
</style> 

效果展示:
![两张图片重叠互换效果展示](https://img-blog.csdnimg.cn/20210808151036671.gif)
评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流