![](/img/trans.png)
[英]Flex-basis is not acting as width when set within display: flex set to flex-direction: row
[英]CSS flex-basis not working when flex-direction is 'column'
我的目标是使用flexbox创建一个双列布局,其中第一列有两行,第二列有一行,如下所示:
设置flex-basis: 100%
第三项上的flex-basis: 100%
给出了所需的效果,但仅当容器的flex-direction
为row
:
将flex-direction
更改为column
导致以下结果,除非明确设置height
,这在我的项目中是不可行的:
如何在不明确设置容器height
的情况下获取第一张图像?
body { display: flex; height: 100px; width: 100px; } .container { display: flex; flex-direction: column; /* Setting this to `row` gives the expected effect,but rotated */ flex-grow: 1; flex-wrap: wrap; /* height: 100%; */ /* Setting this fixes the problem, but is infeasible for my project*/ } .item { flex-grow: 1; } .one { background-color: red; } .two { background-color: blue; } .three { background-color: green; flex-basis: 100%; }
<div class="container"> <div class="item one"> </div> <div class="item two"> </div> <div class="item three"> </div> </div>
为什么它不起作用 :
Flex包装仅在Flex项目的初始主要大小溢出Flex容器时发生。 在flex-direction: row
的情况下,这是当它们的flex项比容器宽时。 对于flex-direction: column
,它们必须溢出容器的高度。
但在CSS中,高度的表现与宽度基本不同。 CSS中容器的高度由其子项的高度决定。 因此,如果没有限制容器高度的东西 ,它们的柔性物品永远不会溢出; 他们只是让他们的容器更高。 如果它们没有溢出,它们将不会包裹。
可能的方法 :
您必须约束容器的高度。 显而易见的方式(你说的不在桌面上),是设置一个明确的height
或max-height
。
问问自己为什么需要限制高度。 它是否留在视口内? 您可以使用视口相对单位并设置类似max-height: 100vh
。 它是否等于此flex容器外的另一列的高度? 您可以使用另一个Flexbox约束它。 使此Flex容器成为外部Flexbox中的flex项。 但是,外部flexbox中的其他东西必须确定其高度。
在更改方向时,尝试为容器内的块设置flex: none
( @media
等)
我在Chrome和Firefox中测试过它。
据我所知,以下代码给出了你想要的结果:
body {
display: flex;
height: 100px;
width: 100px;
}
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
flex-grow:1;
}
.item {
flex-basis:50%;
}
.one {
background-color: red;
}
.two {
background-color: blue;
}
.three {
background-color: green;
flex-basis:100%;
}
除了flex-basis:50%;
此代码等于您在plunker中使用的代码。 由于某些原因,plunker不支持flex-basis
,另见:
我认为您应该使用网格系统来构建您的布局。 在你的第一张照片上,我们可以看到2个cols:第一个col是红色和蓝色框,第二个col是绿色框。
然后结构应该是这样的:
<div class="flex-container">
<div class="col column">
<div class="content red"></div>
<div class="content blue"></div>
</div>
<div class="col">
<div class="content green"></div>
</div>
</div>
使用这些样式:
.flex-container {
display:flex;
}
.col {
flex:1;
display:flex;
}
.column {
flex-direction:column;
}
.content {
flex:1;
}
以下是使用您的演示目标的快速代码: https : //jsfiddle.net/wyyLvymL/希望它有所帮助! (如果你需要了解它是如何工作的,请ping我)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.