如何創建:圖像覆蓋圖標

學習如何在鼠標懸停時創建圖像覆蓋圖標效果。

圖像覆蓋圖標

請將鼠標懸停在圖像上,即可查看疊加效果。

親自試一試

如何創建覆蓋圖像圖標

第一步 - 添加 HTML:

<!-- 添加圖標庫 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
  <img src="img_avatar.png" alt="Avatar" class="image">
  <div class="overlay">
    <a href="#" class="icon" title="User Profile">
      <i class="fa fa-user"></i>
    </a>
  </div>
</div>

第二步 - 添加 CSS:

/* 需要放置覆蓋層的容器。根據需要調整寬度 */
.container {
  position: relative;
  width: 100%;
  max-width: 400px;
}
/* 使圖像可響應 */
.image {
  width: 100%;
  height: auto;
}
/* 疊加效果(全高和全寬)- 位于容器頂部和圖像上方 */
.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .3s ease;
  background-color: red;
}
/* 當您將鼠標懸停在容器上時,疊加圖標會淡入 */
.container:hover .overlay {
  opacity: 1;
}
/* 覆蓋層內的圖標在垂直和水平方向上均居中定位 */
.icon {
  color: white;
  font-size: 100px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  text-align: center;
}
/* 當鼠標移動到圖標上時,改變顏色 */
.fa-user:hover {
  color: #eee;
}

親自試一試

相關頁面

教程:CSS 圖像

教程:如何創建圖像疊加懸停效果