2016-06-15 21 views
1

我有一个flexbox容器,它有4个元素:C1,C2,C3,C4。将flex项移动到最下一行的最右边

目前,它全部显示在一行中。

我的目标是让C4在C3下显示。

有人可以指导我如何实现我的目标?提前致谢。

下面是我的代码:https://jsfiddle.net/vvqhejt3/3/

.flexbox { 
 
    display: flex; 
 
    border: 1px solid black; 
 
    width: 330px; 
 
} 
 
.content1 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: blue; 
 
    height: 50px; 
 
} 
 
.content2 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: yellow; 
 
} 
 
.content3 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: red; 
 
} 
 
.content4 { 
 
    width: 100px; 
 
    background-color: green; 
 
    height: 10px; 
 
}
<div class="flexbox"> 
 
    <div class="content1">C1</div> 
 
    <div class="content2">C2</div> 
 
    <div class="content3">C3</div> 
 
    <div class="content4">C4</div> 
 
</div>

回答

3

当您创建Flex容器(display: flexdisplay: inline-flex),它带有几个默认设置。其中有:

  • flex-direction: row - 柔性项目将调整水平
  • justify-content: flex-start - 柔性项目会叠加在该行的开始
  • align-items: stretch - 柔性项目将扩大到覆盖容器的横尺寸
  • flex-wrap: nowrap - 柔性的项目被迫留在单行

注意最后设置。

你的四个divs被迫留在一行。

您可以用flex-wrap: wrap覆盖此设置。您可以使用auto margin将项目向右分隔。

.flexbox { 
 
    display: flex; 
 
    flex-wrap: wrap;   /* NEW */ 
 
    border: 1px solid black; 
 
    width: 330px; 
 
} 
 

 
.content1 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: blue; 
 
    height: 50px; 
 
} 
 

 
.content2 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: yellow; 
 
} 
 

 
.content3 { 
 
    width: 100px; 
 
    margin-right: 10px; 
 
    background-color: red; 
 
} 
 

 
.content4 { 
 
    width: 100px; 
 
    background-color: green; 
 
    height: 10px; 
 
    margin-left: auto;   /* NEW */ 
 
    margin-right: 10px;  /* NEW */ 
 
}
<div class="flexbox"> 
 
    <div class="content1"> C1 </div> 
 
    <div class="content2"> C2 </div> 
 
    <div class="content3"> C3 </div> 
 
    <div class="content4"> C4 </div> 
 
</div>

参考文献:

1

添加flex-flow: row wrap;justify-content: flex-end;到容器和margin-right: 10px;到DIV类.content4。另外请务必纠正最后一个容器中的类。目前它说conten4

此外,这里是一个简单的指导flexbox的链接。 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

HTML

<div class="flexbox"> 
    <div class="content1"> C1 </div> 

    <div class="content2"> C2 </div> 

    <div class="content3"> C3 </div> 

    <div class="content4"> C4 </div> 
</div> 

CSS

.flexbox { 
    display: flex; 
    border: 1px solid black; 
    width: 330px; 
    flex-flow: row wrap; 
    justify-content: flex-end; 
} 

.content1 { 
    width: 100px; 
    margin-right: 10px; 
    background-color: blue; 
    height: 50px; 
} 

.content2 { 
    width: 100px; 
    margin-right: 10px; 
    background-color: yellow; 
} 

.content3 { 
    width: 100px; 
    margin-right: 10px; 
    background-color: red; 
} 

.content4 { 
    width: 100px; 
    background-color: green; 
    height: 10px; 
    margin-right: 10px; 
}