如何设置flex-box css的两个方向?

时间:2015-08-07 03:09:24

标签: css flexbox

我可以使用1个柔性容器和4个柔性物品来制作此柔性盒方向

-----  ----- -----
| 1 |  |   | |   |
-----  | 3 | | 4 |
-----  |   | |   |
| 2 |  |   | |   |
-----  ----- -----

2 个答案:

答案 0 :(得分:2)

使用12周围的容器,您可以这样做:

* {
    box-sizing: border-box;
}
.wrapper {
    display: flex;
    flex-direction: row;
}
.container {
    flex-direction: column;
    flex-grow: 1;
}
.item  {
    background: tomato;
    color: white;
    font-weight: bold;
    font-size: 3em;
    text-align: center;
    flex-grow: 1;
    border: 1px solid black;
}
.inner {
    height: 100px;
    line-height: 100px;
}
.outer {
    height: 200px;
    line-height: 200px;
}
<div class="wrapper">
    <div class="container">
        <div class="item inner">1</div>
        <div class="item inner">2</div>
    </div>
    <div class="item outer">3</div>
    <div class="item outer">4</div>
</div>

但是如果你不想使用12的容器,恐怕你不能这样做,因为孩子的方向是由父母决定的。

.container {
   flex-direction: row | row-reverse | column | column-reverse;
}

最好的方法是使用属性align-self,这样可以为各个弹性项覆盖默认对齐方式(或者对齐项目指定的对齐方式)。像这样:

* {
    box-sizing: border-box;
}
.wrapper {
    display: flex;
    flex-direction: row;
}
.item  {
    background: tomato;
    color: white;
    font-weight: bold;
    font-size: 3em;
    text-align: center;
    flex-grow: 1;
    border: 1px solid black;
}
.inner {
    height: 100px;
    line-height: 100px;
}
.outer {
    height: 200px;
    line-height: 200px;
}

.item-top{
    align-self: flex-start;
}
.item-bottom{
    align-self: flex-end;
}
<div class="wrapper">
    <div class="item inner item-top">1</div>
    <div class="item inner item-bottom">2</div>
    <div class="item outer">3</div>
    <div class="item outer">4</div>
</div>

但请注意,float,clear和vertical-align对弹性项目没有影响。

Check this out for a better understanding of flex box.

答案 1 :(得分:0)

与公认的答案相反,此布局无需使用包装容器即可实现,尽管此解决方案需要固定高度

技巧是将容器的flex-direction设置为column,这意味着:

  1. flex-basis的计算将根据容器的高度进行,我们将使用该高度来定位第一个和第二个子容器
  2. flex-wrap将内容包裹在右边,我们将使用它来定位第3个和第4个孩子

示例:

.container {
  height: 10rem;
  width: 30rem;
  background: lightgray;
  
  display: flex;
  /* by setting the flex-direction to "column" the 
  items that won't fit into the vertical space
  will be wrapped to the right */
  flex-direction: column;
  flex-wrap: wrap;
}

.child {
  box-sizing: border-box;
  border: 1px crimson solid;
  font-size: 3rem;
}

.child:nth-child(1),
.child:nth-child(2) {
  /* because we set the container's flex-direction
  to column, the flex-basis will make the children
  occupy the vertical space. In our case, because
  the 1st and the 2nd children are both 50%, they
  fill up the first column completely and push out
  the 3rd and the 4th children */
  flex: 0 1 50%;
}

.child:nth-child(3),
.child:nth-child(4) {
  flex: 0 1 100%;
}
<div class="container">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
</div>