js实现div居中
水平居中
使用 margin: 0 auto 实现水平居中,适用于已知宽度的块级元素。
div {
width: 200px;
margin: 0 auto;
}
通过 Flexbox 实现水平居中,父容器设置 justify-content: center。
.parent {
display: flex;
justify-content: center;
}
垂直居中
使用 Flexbox 实现垂直居中,父容器设置 align-items: center。

.parent {
display: flex;
align-items: center;
height: 300px; /* 需要明确高度 */
}
通过绝对定位和 transform 实现垂直居中,不依赖父容器高度。
div {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
水平垂直居中
结合 Flexbox 的 justify-content 和 align-items 实现完全居中。

.parent {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
使用绝对定位和 transform 实现完全居中,适用于未知宽高的元素。
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Grid 布局居中
通过 CSS Grid 的 place-items 属性快速实现居中。
.parent {
display: grid;
place-items: center;
height: 300px;
}






