js 实现 图片居中
使用 CSS Flexbox 实现图片居中
将图片容器设置为 Flex 布局,通过 justify-content 和 align-items 属性实现水平和垂直居中。
<div class="container">
<img src="image.jpg" alt="Centered Image">
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 可根据需要调整高度 */
}
使用 CSS Grid 实现图片居中
通过 Grid 布局的 place-items 属性快速实现居中效果。

.container {
display: grid;
place-items: center;
height: 100vh;
}
使用绝对定位实现图片居中
结合绝对定位和 transform 属性实现精确居中。
.container {
position: relative;
height: 100vh;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用 text-align 实现水平居中
适用于行内元素或 inline-block 元素的水平居中。

<div class="container">
<img src="image.jpg" alt="Centered Image">
</div>
.container {
text-align: center;
}
使用 margin 自动实现居中
适用于已知尺寸的块级元素居中。
img {
display: block;
margin: 0 auto;
width: 300px; /* 需要指定宽度 */
}
使用 JavaScript 动态计算居中位置
通过 JavaScript 计算并设置图片位置实现动态居中。
<img id="centered-image" src="image.jpg" alt="Centered Image">
function centerImage() {
const img = document.getElementById('centered-image');
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
const imgHeight = img.clientHeight;
const imgWidth = img.clientWidth;
img.style.position = 'absolute';
img.style.top = `${(windowHeight - imgHeight) / 2}px`;
img.style.left = `${(windowWidth - imgWidth) / 2}px`;
}
window.addEventListener('load', centerImage);
window.addEventListener('resize', centerImage);






