javascript - 使用 flexbox 对齐项目
问题描述
以下是与position: relative
and一起正常工作的代码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>
解决方案
您可以使用负边距来调整重叠。添加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>
推荐阅读
- ios - webview从远程加载pdf文件然后如何通过邮件发送这个pdf文件等等?(斯威夫特 4)
- jenkins - sonarqube 只有最新的提交应该被扫描
- facebook - Facebook Graph API - 访问用户照片时如何避免请求限制?
- powerapps - 使用列表中的字段而不在表单上可见的数据卡中使用它
- vba - 如何填充文件的最后保存用户和最后保存日期
- firebase - 管理员用户和身份验证用户 Firebase 数据库的读写权限规则
- javascript - 使用 JavaScript 或 TypeScript 做出反应?
- r - 如何按名称、列索引和同时删除列来对数据框进行子集化
- android - Android Studio 崩溃后出现“无效的符号名称”
- c# - 如何在我自己的类中配置依赖注入