防止弹性项目从一边到另一边呈现

我正在使用flexbox将一些项目放在一个块中,但是我希望每个项目都在自己的行中。 例如,我想要橙色方块在文本上方,但是在使用flex之后,它将它移动到文本的一边 – 有没有人知道这个方法?

.container { height: 200px; width: 200px; background: cornflowerblue; position: relative; } .inner { height: 100%; position: absolute; left: 0; width: 100%; top: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; } .square { width: 30px; height: 30px; background: tomato; display: block; } 
 <div class="container"> <div class="inner"> <div class="square"></div> <p>some text</p> </div> </div> 

添加这个样式:

 .inner { flex-direction: column; } 

这就告诉Flexbox在行中而不是在列中显示其子项。 (我知道,很奇怪,对吧?)

更新后的代码片段:

 .container { height: 200px; width: 200px; background: cornflowerblue; position: relative; } .inner { height: 100%; position: absolute; left: 0; width: 100%; top: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; flex-direction: column; } .square { width: 30px; height: 30px; background: tomato; display: block; } 
 <div class="container"> <div class="inner"> <div class="square"></div> <p>some text</p> </div> </div> 

flex容器的初始设置是flex-direction: row 。 这意味着每当你给一个元素display: flex或者display: inline-flex ,默认情况下,这个元素的所有元素将水平排列。

您可以使用flex-direction: column覆盖此默认值flex-direction: column

 .container { height: 200px; width: 200px; background: cornflowerblue; position: relative; } .inner { height: 100%; position: absolute; left: 0; width: 100%; top: 0; display: flex; align-items: center; justify-content: center; flex-direction: column; /* NEW */ } .square { width: 30px; height: 30px; background: tomato; display: block; } 
 <div class="container"> <div class="inner"> <div class="square"></div> <p>some text</p> </div> </div>