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

如何使用Flexbox实现一个元素居中、另一个居右的布局?

实现Header内h1居中、div居右的Flexbox布局方案

你当前的写法存在两个关键问题:

  1. justify-self: right是Grid布局专属属性,Flexbox容器不支持该属性,设置后不会生效。
  2. justify-content: center会让容器内所有子元素整体居中,无法单独控制某个元素居右。

正确解决方案(推荐)

利用margin-left: auto实现div自动居右,同时保持h1居中:

HTML代码

<header class="header">
     <h1>This is a heading</h1>
     <div>this is my div</div>
</header>

Sass代码

.header {
  display: flex;
  justify-content: center; /* 让h1在剩余空间中居中 */
  align-items: center; /* 可选:让元素垂直居中,按需调整 */
  
  div {
    margin-left: auto; /* 核心:自动填充左侧所有剩余空间,将div挤到右侧 */
    border: 1px solid black;
  }
}

转换后的CSS代码

.header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.header div {
  margin-left: auto;
  border: 1px solid black;
}

原理说明

在Flex容器中,margin-left: auto会触发元素自动占据其左侧的所有可用空间,从而将自身推到容器最右侧。而justify-content: center会让h1在容器剩余的中间空间里保持居中,刚好满足布局需求。

内容的提问来源于stack exchange,提问作者Rahul Pratap Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:54:27