要实现两个大小不同的 div
在父容器中居中叠加,可以使用 CSS 的 flexbox
或 grid
布局,并结合 position
属性来实现。以下是两种常见的实现方式:
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
position: relative; /* 使子元素的绝对定位相对于父元素 */
width: 100%; /* 父容器宽度 */
height: 100vh; /* 父容器高度 */
}
.child1, .child2 {
position: absolute; /* 绝对定位,使两个 div 叠加 */
}
.child1 {
width: 200px;
height: 200px;
background-color: red;
}
.child2 {
width: 100px;
height: 100px;
background-color: blue;
}
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
.parent {
display: grid;
place-items: center; /* 水平和垂直居中 */
position: relative; /* 使子元素的绝对定位相对于父元素 */
width: 100%; /* 父容器宽度 */
height: 100vh; /* 父容器高度 */
}
.child1, .child2 {
position: absolute; /* 绝对定位,使两个 div 叠加 */
}
.child1 {
width: 200px;
height: 200px;
background-color: red;
}
.child2 {
width: 100px;
height: 100px;
background-color: blue;
}
flexbox
或 grid
布局来使子元素居中。justify-content: center
和 align-items: center
用于在 flexbox
中居中,place-items: center
用于在 grid
中居中。position: absolute
使两个 div
叠加在一起。由于父容器设置了 position: relative
,子元素的绝对定位会相对于父容器进行定位。div
:通过设置不同的 width
和 height
来区分两个 div
的大小。这两种方法都可以实现两个大小不同的 div
在父容器中居中叠加的效果。你可以根据项目需求选择适合的布局方式。