js实现div居中
使用 Flexbox 布局实现居中
将父容器设置为 Flex 布局,通过 justify-content 和 align-items 属性实现水平和垂直居中。
<div class="container">
<div class="centered-div">居中内容</div>
</div>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 确保容器有高度 */
}
使用 Grid 布局实现居中
利用 CSS Grid 的 place-items 属性快速实现居中效果。
.container {
display: grid;
place-items: center;
height: 100vh;
}
使用绝对定位实现居中
通过绝对定位结合 transform 属性实现精准居中。
.centered-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
使用 JavaScript 动态计算居中
通过 JavaScript 动态计算位置实现居中,适用于需要动态调整的场景。
<div id="centeredDiv">动态居中内容</div>
function centerDiv() {
const div = document.getElementById('centeredDiv');
const windowHeight = window.innerHeight;
const windowWidth = window.innerWidth;
const divHeight = div.offsetHeight;
const divWidth = div.offsetWidth;
div.style.position = 'absolute';
div.style.top = (windowHeight - divHeight) / 2 + 'px';
div.style.left = (windowWidth - divWidth) / 2 + 'px';
}
window.addEventListener('load', centerDiv);
window.addEventListener('resize', centerDiv);
使用文本居中实现简单居中
适用于单行文本或行内元素的简单居中方案。
.container {
text-align: center;
line-height: 100vh; /* 垂直居中 */
}
使用 margin 自动实现水平居中
通过设置左右 margin 为 auto 实现水平居中,需指定宽度。
.centered-div {
width: 50%;
margin: 0 auto;
}
以上方法可根据具体需求选择,Flexbox 和 Grid 是现代布局的首选方案,兼容性良好且代码简洁。







