1920×900 大圖在 1024×768 視窗中,若直接 <img> 引入會撐破佈局;若作為 background-image 則需解決「覆蓋容器」與「水平垂直居中」雙重需求。
.hero-banner {
width: 100%;
height: 400px; /* 固定高度或 vh 單位 */
background-image: url('large.jpg');
background-repeat: no-repeat;
background-position: center center; /* 關鍵:水平垂直居中 */
background-size: cover; /* 關鍵:等比縮放覆蓋 */
}
| 屬性 | 值 | 作用 |
|---|---|---|
background-size | cover | 等比縮放圖片,使其寬高均 ≥ 容器,完全覆蓋(可能裁切) |
contain | 等比縮放,使圖片完整顯示於容器內(可能留白) | |
background-position | center center | 水平垂直置中;可用百分比 50% 50% 或關鍵字 |
50% 118px | 水平置中,垂直偏移 118px(適配固定導航欄等場景) |
若需保持 <img> 語義(SEO、無障礙、列印),使用 Flexbox/Grid 置中:
.img-container {
width: 100%;
height: 400px;
overflow: hidden; /* 裁切超出部分 */
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
}
.img-container img {
width: 100%; /* 或 max-width: 100% */
height: 100%;
object-fit: cover; /* 等比覆蓋,同 background-size: cover */
object-position: center; /* 置中對齊 */
}
object-fit 享有優異的現代瀏覽器支援(IE 需 Polyfill),是替代背景圖的首選語義化方案。
<section class="hero" aria-label="首頁主視覺">
<div class="hero__bg" style="background-image: url('hero-1920.jpg')"></div>
<div class="hero__content">
<h1>產品標語</h1>
<a href="#cta" class="btn">立即體驗</a>
</div>
</section>
.hero {
position: relative;
width: 100%;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: #fff;
}
.hero__bg {
position: absolute;
inset: 0;
background-size: cover;
background-position: center;
z-index: -1;
/* 可選:添加漸層遮罩增強文字對比 */
background-image:
linear-gradient(rgba(0,0,0,.4), rgba(0,0,0,.4)),
url('hero-1920.jpg');
}
<picture> + srcset 提供不同解析度圖源,避免行動裝置下載 1920px 原圖。type="image/webp" 回退。loading="lazy" 或 IntersectionObserver。<head>,消除渲染阻塞。background-size: cover 是否生效,容器是否有明確高度。height 不為 auto,或改用 Flex/Grid 置中。