萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 實現文字層浮動在圖片上方:絕對定位與層疊上下文實戰

實現文字覆蓋在圖片上方(如圖片標題、描述、價格標籤),核心在於父容器建立定位上下文,子元素絕對定位配合層疊順序控制。

核心代碼結構

<div class="image-wrapper">
  <img src="product.jpg" alt="商品圖片">
  <div class="image-overlay">
    商品標題與描述信息
  </div>
</div>

CSS 關鍵樣式

.image-wrapper {
  position: relative;           /* 關鍵:建立定位上下文 */
  width: 251px;                 /* 圖片寬度 */
  height: 330px;                /* 圖片高度 */
  display: inline-block;        /* 適配圖片尺寸 */
}

.image-wrapper img {
  display: block;               /* 消除底部間隙 */
  width: 100%;
  height: 100%;
  object-fit: cover;            /* 現代:保持比例填滿 */
}

.image-overlay {
  position: absolute;           /* 相對父容器定位 */
  left: 0;
  bottom: 0;                    /* 底部對齊 */
  width: 100%;
  height: 54px;                 /* 固定高度或自適應 */
  line-height: 54px;
  color: #fff;
  background: rgba(0, 0, 0, 0.7);  /* 半透明黑背景 */
  overflow: hidden;             /* 內容超出隱藏 */
  text-indent: 15px;            /* 文字左側留白 */
  z-index: 1;                   /* 確保在圖片之上 */
}

關鍵技術點解析

技術點 代碼 作用
父容器相對定位 position: relative 建立定位基準,子元素 absolute 相對此定位
子元素絕對定位 position: absolute 脫離文檔流,不佔據空間
底部對齊 bottom: 0; left: 0; width: 100% 固定在容器底部橫向鋪滿
半透明背景 rgba(0,0,0,0.7) 文字可讀性與圖片可見性平衡
層疊順序 z-index: 1 確保覆蓋在圖片(z-index: auto/0)之上
圖片填滿容器 object-fit: cover 現代 CSS,避免圖片變形

進階變體:懸停顯示覆蓋層


.image-wrapper .image-overlay {
  opacity: 0;
  transform: translateY(100%);  /* 初始隱藏在底部外 */
  transition: all 0.3s ease;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
  transform: translateY(0);     /* 滑入視圖 */
}

多層疊加:標籤 + 標題 + 操作按鈕


.image-overlay {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  padding: 12px;
  height: auto;
  min-height: 60px;
}

.overlay-tag {
  font-size: 11px;
  background: #ff6600;
  color: #fff;
  padding: 2px 6px;
  border-radius: 3px;
  align-self: flex-start;
  margin-bottom: 6px;
}

.overlay-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
}

.overlay-actions {
  display: flex;
  gap: 8px;
}

.overlay-btn {
  flex: 1;
  padding: 6px 0;
  background: rgba(255,255,255,0.2);
  border: 1px solid rgba(255,255,255,0.5);
  color: #fff;
  border-radius: 4px;
  font-size: 12px;
  transition: background 0.2s;
}
.overlay-btn:hover { background: rgba(255,255,255,0.4); }

響應式適配


@media (max-width: 480px) {
  .image-wrapper { width: 100%; height: auto; }
  .image-overlay { 
    position: static;  /* 移動端改為文檔流內 */
    background: #f5f5f5;
    color: #333;
    padding: 12px;
  }
}

無障礙增強


/* 確保鍵盤可訪問 */
.image-wrapper:focus-within .image-overlay {
  opacity: 1;
  transform: translateY(0);
}

/* 螢幕閱讀器可讀 */
.image-overlay { 
  /* 不用 display:none 隱藏,用 opacity/transform */
}
copyright © 萬盛學電腦網 all rights reserved