You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS Flex布局中如何将绿色方块移动到容器右侧末尾位置

问题原因

.container2设置为纵向flex布局后,子元素默认沿水平交叉轴左对齐,因此绿色方块默认显示在容器左侧,仅需少量CSS修改即可实现绿色方块靠右的预期效果。

实现方案
  • 方案1(最小改动,不影响其他元素):给.green类添加align-self: flex-end属性,仅控制绿色方块自身沿水平方向靠右对齐,紫色方块保持原有左对齐状态,完全匹配目标效果。
  • 方案2:给.green类添加margin-left: auto属性,自动填充水平方向剩余空白,将绿色方块推至容器最右侧。
核心修改代码

以方案1为例,仅需修改绿色方块的样式:

.green {
  background-color: rgb(99, 151, 99);
  width: 200px;
  height: 200px;
  /* 新增下方一行代码即可 */
  align-self: flex-end;
}
效果对比
  • 当前实际运行效果:
    当前实际效果
  • 目标预期效果:
    目标预期效果
完整可运行代码
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  margin-bottom: 50px;
}

.container2 {
  border: 3px solid gray;
  width: 600px;
  height: 600px;
  text-align: center;
  display: flex;
  flex-direction: column;
}

.purple {
  background-color: rgb(202, 117, 202);
  width: 200px;
  height: 200px;
}

.green {
  background-color: rgb(99, 151, 99);
  width: 200px;
  height: 200px;
  align-self: flex-end;
}

.spacing {
  height: 200px;
}
<div class="container">
  <div class="container2">
    <div class="purple"></div>
    <div class="spacing"></div>
    <div class="green"></div>
  </div>
</div>

内容的提问来源于stack exchange,提问作者Stuywesant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:09:15