.center-box {
position: fixed; left: 50%; top: 50%;
transform: translate(-50%, -50%);
/* 或 flex 容器 */
display: flex; justify-content: center; align-items: center;
}
function centerImage(imgId) {
var $img = $('#' + imgId);
var w = $img.width(), h = $img.height();
var vw = $(window).width(), vh = $(window).height();
$img.css({position: 'absolute', left: (vw - w)/2, top: (vh - h)/2});
}
// 圖片載入後執行
$('#imgId').on('load', function(){ centerImage(this.id); });
$(window).on('resize', function(){ centerImage('imgId'); });
<img id="myImg" src="photo.jpg" style="display:none;" />
<script>
$('#myImg').on('load', function(){
$(this).show();
centerImage('myImg');
});
</script>
| 方案 | 相容性 | 優點 | 缺點 |
|---|---|---|---|
| CSS transform | IE9+ | 無 JS、效能佳、支援動畫 | IE8 不支援 |
| CSS flex/grid | IE10+ | 語意清晰、容器置中 | 需容器高度 |
| JS 計算 | 全瀏覽器 | 完全控制、可動態調整 | 需監聽 load/resize、重排成本 |
現代專案優先用 CSS transform 或 flex;僅在必須支援 IE8 時才加入 JS 兜底。