【问题标题】:How can I align 2 first elements on the left and the last one on the right [duplicate]如何对齐左侧的第一个元素和右侧的最后一个元素[重复]
【发布时间】:2019-08-21 00:30:12
【问题描述】:

我认为我的代码是有序的,但我不知道为什么我无法以这种方式组织我的元素:

|**   *|

这是我的代码:

.container {
  border: 1px solid red;
  display: flex;
  justify-content: flex-start;
  width: 100%;
  height: 200px;
  flex-direction: row;
}

.container div {
  border: 1px solid blue;
  height: 100px;
  width: 100px;
}

.right {
  display: flex;
  align-self: flex-end;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>
  <div class="right">
    3
  </div>
</div>

我做错了什么?这是我的实时代码:https://jsfiddle.net/uxpkh9nL/

【问题讨论】:

  • 我没有兄弟

标签: html css flexbox centering


【解决方案1】:

而不是align-self: flex-end(在行flex-direction中,align-selfalign-items交叉轴中对齐flex项这意味着垂直) - 您可以在 right 元素上使用 margin-left: auto - 请参见下面的演示:

.container{
  border:1px solid red;
  display:flex;
  justify-content:flex-start;
  width:100%;
  height: 200px;
  flex-direction:row;
}
.container div{
  border:1px solid blue;
  height: 100px;
  width: 100px;
}

.right{
  display:flex;
  /*align-self:flex-end;*/
  margin-left: auto; /* added */
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>  
  <div class="right">
    3
  </div>  
</div>

在这种情况下我更喜欢使用边距,但您也可以使用 伪元素 并使用 分隔项目 并在其上使用 flex-grow: 1

  • order: 1 添加到flex 项,将order: 2 添加到伪元素,将order: 3 添加到right 元素位置 按该顺序排列的弹性项目。

  • flex-grow: 1 添加到伪元素 会强制其填充所有剩余空间,从而right 元素放在右端。

但如果你问我,这有点过头了 - 请参阅下面的演示:

.container{
  border:1px solid red;
  display:flex;
  justify-content:flex-start;
  width:100%;
  height: 200px;
  flex-direction:row;
}
.container div{
  border:1px solid blue;
  height: 100px;
  width: 100px;
  order: 1; /* added */
}

.right{
  display:flex;
  /*align-self:flex-end;*/
  order: 3 !important; /* added */
}

.container:after { /* added */
  order: 2;
  content: '';
  display: block;
  flex-grow: 1;
}
<div class="container">
  <div>
    1
  </div>
  <div>
    2
  </div>  
  <div class="right">
    3
  </div>  
</div>

【讨论】:

  • 它可以工作,但是......有没有办法用 flexbox 来实现它?
  • 你在 flexbox 中没有任何justify-self - flex 轴 与边距对齐 flexbox way :) 将为答案添加另一个选项...
  • 我只是在学习 flexbox,你所做的对我来说很复杂,你可以详细说明一下,因为你是最好的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-11
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 2021-04-09
  • 1970-01-01
相关资源
最近更新 更多