既然flexbox没有 justify-self ,如何实现一左一中布局?

想用flexbox实现下边header中“返回”在左,“这是标题”在中的效果。
task_1_11_1.jpg

本来想这样就可以:

header{
    display:flex;
    justify-content:center;
}
back_link{
    justify-self:flex-start;
}

然后发现原来flexbox是没有justify-self的。
查了下倒是可以用margin:auto 调整item单独位置。但只适用于一左一右的情况,无法一左一中。
我目前能想到的就是加一个空的div,然后在header里用justify-content:space-between……
倒是可以实现,但肯定不是好办法
想问下各位有什么建议? 不是flexbox但非常好用的也行。

阅读 28.3k
11 个回答

这个没必要用flex来做

<div style="
    position: relative;
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: red;
    text-align: center;
">
      <span style="
    position: absolute;
    left: 0;
    top: 0;
    display: inline-block;
    line-height: 30px;
">返回返回返回返回</span>
      <span>这是标题</span>
    </div>

clipboard.png

我通常是这么做的:外层 header的 position 为 relative,居中的标题 position: absolute, left: 50% margin-left偏移标题一半的距离

flexbox还真没想出来,估计就算做,代码也很丑。还不如傻瓜方案来的轻松:

html, body{
  width: 100%;
}

.header {
  width: 100%;
  text-align: center;
}

.back{
  float: left;
}
<div class="header">
    <span class="back">返回</span>
    <span class="title">这是标题</span>
</div>

demo: Plunker

除了一些舊有的方式外,Flex 的話估計是用 3 個 item 切割成三份比教單純,除了多加一個空的不然就是剩餘的規劃成 2

.button {
  flex: 1
}

.title {
  flex: 2
}

再者就是 Grid

这个使用flex是能够实现的,先center全部到中间,然后给最左边一个 margin-left:auto 就行

<style>
.header {
  display: flex;
}
.back {
  width: 3em; /*固定宽度,随便写的数值*/
}
.title {
  flex: 1;
  text-align: center;
}
</style>
<header class="header">
    <div class="back">返回</div>
    <div class="title">标题</div>
</header>

只要知道左边宽度就行了~你可以这么写~

.header{
    display:flex;
    justify-content:center;
}
.back_link{
    justify-self:flex-start;
    width: .4rem;
}
.title{
    flex:1;
    margin-left: -.4rem
}

现在是2018,你说的这两个属性都有,只是不少浏览器不实现,尤其是移动端。其中align-self在桌面端基本没问题,而你用到的justify-slef在dge和firefox桌面端已经实现(2018.1)

这个不用flex或许更简单。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题