實現文字覆蓋在圖片上方(如圖片標題、描述、價格標籤),核心在於父容器建立定位上下文,子元素絕對定位配合層疊順序控制。
<div class="image-wrapper">
<img src="product.jpg" alt="商品圖片">
<div class="image-overlay">
商品標題與描述信息
</div>
</div>
.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 */
}