3 回答
TA贡献1725条经验 获得超7个赞
您可以使用负边距来调整重叠。添加margin-left: -50px;以box4达到所需的输出。
* { box-sizing: border-box; }
.container { width: 300px; height: 300px; border: 1px solid black; }
.green { background: #2a9d8f; }
.blue { background: #333366; }
/* Position CSS */
.position-container { position: relative; }
.box1, .box2 { position: absolute; }
.box1 { width: 60px; height: 60px; left: 120px; top: 120px; }
.box2 { width: 40px; height: 40px; left: 130px; top: 130px; }
/* Flexbox CSS */
.flex-container {
display: flex;
align-items: center;
justify-content: center;
}
.box3 { width: 60px; height: 60px; }
.box4 { width: 40px; height: 40px; margin-left: -50px; }
<div class="container position-container">
<div class="box1 green"></div>
<div class="box2 blue"></div>
</div>
<hr />
<div class="container flex-container">
<div class="box3 green"></div>
<div class="box4 blue"></div>
</div>
TA贡献1757条经验 获得超7个赞
如果你想达到相同的效果但仅使用flexbox,我认为你不能这样做,但你需要将位置与flexbox一起使用,如下代码所示:
* {
box-sizing: border-box;
}
.container {
width: 300px;
height: 300px;
border: 1px solid black;
}
.green {
background: #2a9d8f;
}
.blue {
background: #333366;
}
/* Position CSS */
.position-container {
position: relative;
}
.box1,
.box2 {
position: absolute;
}
.box1 {
width: 60px;
height: 60px;
left: 120px;
top: 120px;
}
.box2 {
width: 40px;
height: 40px;
left: 130px;
top: 130px;
}
/* Flexbox CSS */
.flex-container {
display: flex;
align-items: center;
justify-content: center;
}
.box3 {
width: 60px;
height: 60px;
position: absolute;
}
.box4 {
width: 40px;
height: 40px;
position: absolute;
}
<div class="container position-container">
<div class="box1 green"></div>
<div class="box2 blue"></div>
</div>
<hr />
<div class="container flex-container">
<div class="box3 green"></div>
<div class="box4 blue"></div>
</div>
TA贡献1859条经验 获得超6个赞
您应该更改 HTML 并将蓝色框放在绿色框内。然后,为绿色框添加 css: .box3 { display: flex; align-items: center; justify-content: center; }
* { box-sizing: border-box; }
.container { width: 300px; height: 300px; border: 1px solid black; }
.green { background: #2a9d8f; }
.blue { background: #333366; }
/* Position CSS */
.position-container { position: relative; }
.box1, .box2 { position: absolute; }
.box1 { width: 60px; height: 60px; left: 120px; top: 120px; }
.box2 { width: 40px; height: 40px; left: 130px; top: 130px; }
/* Flexbox CSS */
.flex-container {
display: flex;
align-items: center;
justify-content: center;
}
.box3 { width: 60px; height: 60px; display: flex; align-items: center; justify-content: center; }
.box4 { width: 40px; height: 40px; }
<div class="container position-container">
<div class="box1 green"></div>
<div class="box2 blue"></div>
</div>
<hr />
<div class="container flex-container">
<div class="box3 green">
<div class="box4 blue"></div>
</div>
</div>
添加回答
举报