3 回答

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用負(fù)邊距來調(diào)整重疊。添加margin-left: -50px;以box4達(dá)到所需的輸出。
* { 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貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果你想達(dá)到相同的效果但僅使用flexbox,我認(rèn)為你不能這樣做,但你需要將位置與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貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
您應(yīng)該更改 HTML 并將藍(lán)色框放在綠色框內(nèi)。然后,為綠色框添加 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>
添加回答
舉報(bào)