NoD*_*chi 7 html css css3 flexbox
我正在使用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;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="inner">
<div class="square"></div>
<p>some text</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
添加此样式:
.inner {
flex-direction: column;
}
Run Code Online (Sandbox Code Playgroud)
这告诉flexbox在行而不是列中显示其子级。(我知道,很奇怪,对吧?)
更新的代码段:
.inner {
flex-direction: column;
}
Run Code Online (Sandbox Code Playgroud)
.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;
}Run Code Online (Sandbox Code Playgroud)
Flex 容器的初始设置是flex-direction: row。这意味着每当您给出一个元素display: flex或时display: inline-flex,默认情况下该元素的所有 子元素都会水平排列。*
您可以使用以下命令覆盖此默认值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;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="inner">
<div class="square"></div>
<p>some text</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
或者,您可以flex-direction: row通过添加flex-wrap: wrap到容器并为子级提供足够大的宽度(例如width: 100%)来强制每行仅包含一个项目。
.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-wrap: wrap; /* NEW */
align-content: center; /* NEW */
}
.square {
width: 30px;
height: 30px;
background: tomato;
display: block;
}
/* NEW */
p {
flex: 0 0 100%;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<div class="container">
<div class="inner">
<div class="square"></div>
<p>some text</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
* 请注意“儿童”一词。子级之外的后代不参与弹性布局。