body, .full-bg {
background-image: url('hero.jpg');
background-repeat: no-repeat;
background-position: center center;
background-size: cover; /* 核心:等比縮放完全覆蓋 */
/* 可選:固定背景視差效果 */
background-attachment: fixed; /* 注意:移動端效能/支援度問題 */
}
cover vs contain:
• cover:圖片寬高皆 ≥ 容器,可能裁切。
• contain:圖片完整顯示於容器內,可能留白。
background-position 控制裁切焦點(如 top center 保留人物頭部)。IE8 不支援 background-size,需 JS 方案:
<script src="jquery.min.js"></script>
<script>
$(function() {
function resizeBg() {
var $win = $(window),
winW = $win.width(),
winH = $win.height(),
$img = $('#bg-img');
// 計算等比縮放尺寸
var imgRatio = $img.data('ratio') || ($img[0].naturalWidth / $img[0].naturalHeight);
var winRatio = winW / winH;
if (winRatio > imgRatio) {
$img.css({ width: winW, height: winW / imgRatio, left: 0, top: -(winW/imgRatio - winH)/2 });
} else {
$img.css({ height: winH, width: winH * imgRatio, top: 0, left: -(winH*imgRatio - winW)/2 });
}
}
// 初始化
$('.bd').append('<img id="bg-img" src="hero.jpg" style="position:fixed;z-index:-1;">');
$('#bg-img').on('load', function() {
$(this).data('ratio', this.naturalWidth / this.naturalHeight);
resizeBg();
});
$(window).on('resize', resizeBg);
});
</script>
現代專案**強烈建議放棄 IE8 支援**,若必須支援,請使用 background-size-polyfill (HTC 行為檔) 或上述 JS 方案。
.hero {
background-image:
linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)), /* 深色遮罩 */
url('hero.jpg');
background-size: cover, cover;
background-position: center, center;
}
<picture>
<source media="(min-width: 1200px)" srcset="hero-desktop.jpg">
<source media="(min-width: 768px)" srcset="hero-tablet.jpg">
<img src="hero-mobile.jpg" alt="Hero 圖片">
</picture>
/* CSS 僅需 */
.picture-img { width: 100%; height: 100%; object-fit: cover; }
<picture>
<source type="image/avif" srcset="hero.avif">
<source type="image/webp" srcset="hero.webp">
<img src="hero.jpg" alt="Hero">
</picture>
:root { --bg-url: url('day.jpg'); }
@media (prefers-color-scheme: dark) {
:root { --bg-url: url('night.jpg'); }
}
body { background-image: var(--bg-url); background-size: cover; }
<picture> 回退。loading="lazy" 或 IntersectionObserver 切換 background-image。<head>,避免白屏閃爍。background-repeat: no-repeat。height: 0 或 auto 且無內容撐開),需給容器明確高度或 min-height: 100vh。background-attachment: fixed 失效/卡頓position: fixed 偽元素模擬或放棄視差。background-size: cover 配合 background-attachment: fixed 失效fixed 或用 JS 方案。