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

如何用Flexbox实现父容器内3元素居左、1元素居右?

Flexbox实现3元素居左、1元素居右的布局方案

在Flex布局中,justify-self属性并不生效——Flexbox的主轴对齐逻辑基于容器级的justify-content或元素的margin、flex属性控制,而非单个元素的justify-self。要实现3个元素居左、1个元素居右的效果,最直接的方法是利用自动margin,以下是具体方案:

解决方案:自动margin实现元素居右

给需要居右的元素添加margin-left: auto,它会自动占据容器主轴上的剩余空间,将元素推到右侧。

修改后的CSS代码:

body{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
.container{
    border: 2px solid gray;
    display: flex ;
    flex-direction: row;
    align-items: flex-start;
    width: 600px;
    height: 600px;
}
.item{
    width: 100px;
    background-color: lightgray;
    margin: 2px 0;
    font-size: 40px;
    line-height: 100px;
    text-align: center;
}
.item:nth-child(4){
    background-color: orange;
    align-self: center;
    margin-left: auto; /* 添加该行实现水平居右 */
}

对应的HTML代码保持不变:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
    </div>
</body>
</html>

其他可选方案

如果需要适配更复杂的布局场景,还可以使用以下方法:

  • 占位元素法:在第3个和第4个元素之间添加空元素,设置flex-grow: 1,让其占据剩余空间,将第4个元素挤到右侧。
  • 分组包裹:把前3个元素放在一个子Flex容器中,父容器设置justify-content: space-between,实现左右分组对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:35:20