首页 > 解决方案 > 使用 flexbox 对齐项目

问题描述

以下是与position: relativeand一起正常工作的代码position: absolute。但是,我正在尝试使用来实现类似的效果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; }
.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>
    <div class="box4 blue"></div>
  </div>

标签: javascripthtmlcssflexboxcss-position

解决方案


您可以使用负边距来调整重叠。添加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>


推荐阅读