i有一个flexbox容器,该容器具有4个元素:C1,C2,C3,C4。
目前,它全部显示为一行。
我的目标是使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>
创建Flex容器(display: flex
或display: inline-flex
)时,它会带有多个默认设置。其中包括:
-
flex-direction: row
- flex项目将水平对齐 -
justify-content: flex-start
- flex项目将在行开始时堆叠 -
align-items: stretch
- flex项目将扩展以覆盖容器的杂交 -
flex-wrap: nowrap
-弹性项目被迫留在一行中
注意最后一个设置。
您的四个Div被迫保留在一条线上。
您可以用flex-wrap: wrap
覆盖此设置。
然后,您可以使用自动保证金将项目置于右侧。
.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>
参考:
- 沿主轴对齐弹性项目的方法
- 5.2。弹性线包装:
flex-wrap
属性
将 flex-flow: row wrap;
和 justify-content: flex-end;
添加到容器和 margin-right: 10px;
div class .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;
}