js实现div居中
水平居中与垂直居中
使用 display: 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;
}
绝对定位居中
使用 position: absolute 结合 transform 属性实现居中。

.centered-div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
网格布局居中
使用 CSS Grid 布局的 place-items 属性实现居中。

.container {
display: grid;
place-items: center;
height: 100vh;
}
文本居中
如果只是简单的文本居中,可以使用 text-align 和 line-height 属性。
.centered-div {
text-align: center;
line-height: 100px; /* 等于容器高度 */
}
JavaScript 动态居中
使用 JavaScript 动态计算并设置元素的位置。
function centerDiv(element) {
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const elementWidth = element.offsetWidth;
const elementHeight = element.offsetHeight;
element.style.position = 'absolute';
element.style.left = (windowWidth - elementWidth) / 2 + 'px';
element.style.top = (windowHeight - elementHeight) / 2 + 'px';
}
const div = document.querySelector('.centered-div');
centerDiv(div);






