Flex:如何正确对齐以包裹为中心的项目

时间:2019-07-01 18:13:36

标签: html css flexbox

我想在有足够空间但在包装纸上居中的情况下左对齐两个项目,右对齐一个。

第一次包裹时(太薄,无法放入合适的物品)

  • 右边的项目应该移到下一行并居中
  • 其余部分保持对齐状态

在第二个包装上(太薄,无法容纳右+中间的物品)

  • 所有三个项目都垂直堆叠并居中

尝试使用justify-content包含两层柔韧性:第一层在中间,第二层在中间。

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.subcontainer {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  border: 1px solid black;
  height: 100px;
}
<div class="container">
  <div class="subcontainer">
    <div class="item">abc abc abc abc abc abc</div>
    <div class="item">def def def def def def</div>
  </div>
  <div class="item">right right right</div>
</div>

http://jsfiddle.net/b3z18rLn/9/

不幸的是,正确的物品在包装时不会居中,而是保持对齐。

1 个答案:

答案 0 :(得分:0)

JSFiddle


您可以将第三个项目包装在另一个Flexbox容器中,并使用媒体查询:


/* flex-wrap will put right-subcontainer on a new row when you 
   decrease the viewport's width.*/
.container {
    display: flex;
    flex-wrap: wrap;
}

/* flex-grow of 1 will enable this container to take up the
   entire row when the left and right subcontainers are 
   row by row. 
   
   flex-wrap is used to allow the second item to go onto a
   new row at smaller widths. */
.left-subcontainer {
    display: flex;
    flex-grow: 1;
    flex-wrap: wrap;
}

/* Again, flex-wrap is used to give the right subcontainer 
   the ability to take up the entire row.
   
   flex-end changes the items from positioning left-to-right
   to right-to-left.*/
.right-subcontainer {
    display: flex;
    flex-grow: 1;
    justify-content: flex-end;
}

.item {
    border: 1px solid black;
    width: 300px;
    height: 300px;
}

/* You will need to adjust the arguments for these media queries. 
   Also, if you do decide to use media queries for this approach,
   I would suggest reversing the CSS logic by having the CSS 
   selectors tackle mobile design first and use media queries 
   to tackle design at larger screen sizes. */
   
/* The first wrap/breakpoint is at this width. I am telling the 
   right container to be center-aligned at the first breakpoint. */
@media only screen and (max-width: 925px) {
  .right-subcontainer {
    justify-content: center;
  }
}

/* Then, I tell the left container to be center-aligned at the second
   breakpoint. */
@media only screen and (max-width: 1320px) {
  .left-subcontainer {
    justify-content: center;
  }
}
<div class="container">
    <div class="left-subcontainer">
      <div class="item">abc abc abc abc abc abc</div>
      <div class="item">def def def def def def</div>
    </div>

    <div class="right-subcontainer">
      <div class="item">right right right</div>
    </div>
</div>