如何使用Flexbox对齐一个弹性项目并右对齐另一个弹性项目

时间:2015-10-30 20:48:16

标签: html css css3 flexbox

我是Flexbox的新手,想要对齐按钮,但我看不到如何使用Flexbox处理同一行中心对齐按钮和右对齐按钮的常见情况。

但是,我找到了一种方法,使用与右对齐项目相同长度的不可见左对齐项目和使用window.onload = function() { document.getElementById('iframe1').src = "Secondary.html"; } 的flex justify-content来使中间项目以行为中心

Flexbox有更直接的方法吗?

space-between
.flexcontainer {
  display: flex;
  justify-content: space-between;
  width: 500px;
  height: 200px;
}
.iteminvisible {
  flex: 0 1 auto;
  width: 100px;
  height: 100px;
  visibility: hidden;
}
.itemcenter {
  flex: 0 1 auto;
  width: 150px;
  height: 100px;
  .itemright {
    flex: 0 1 auto;
    width: 100px;
    height: 100px;
  }

2 个答案:

答案 0 :(得分:20)

如您的问题中所述,将justify-content: space-between与不可见的弹性项目一起使用,是实现所需布局的好方法。请注意,如果左侧和右侧项目的长度相等(see demo),则中间项目只能居中。

您可能需要考虑的其他解决方案包括auto marginsabsolute positioning。这种方法的两个好处是不需要额外的标记,并且无论物品尺寸如何都可以实现真正的定心。一个缺点是,居中的项目已从document flow中移除(这可能对您有用,也可能无关紧要。)

.flexcontainer {
      display: flex;
      justify-content: flex-start;   /* adjustment */
      position: relative;            /* new */
      width: 500px;
      height: 200px;
    }

.itemcenter {
      flex: 0 1 auto;
      width: 150px;
      height: 100px; 
      position: absolute;             /* new */
      left: 50%;
      transform: translateX(-50%);
    }

.itemright {
      flex: 0 1 auto;
      width: 100px;
      height: 100px;
      margin-left: auto;              /* new */
    }
<div class="flexcontainer">
  <div class="itemcenter">One</div>
  <div class="itemright">Other</div>
</div>

此处有更多详情:Methods for Aligning Flex Items along the Main Axis(参见方框#62-78)。

答案 1 :(得分:9)

   .container {
      display: flex;
      flex-direction: column; //this will allow flex-end to move item to the right            
      align-items: center;
   }
   .right-item {
      align-self: flex-end;
   }
相关问题