Flex容器计算一列,当有多列时 [英] Flex container calculating one column, when there are multiple columns
问题描述
我有一个 li
15个项目显示为 flex-direction:column
(它应用于父 ul
))。然后我有一个 div
包装 ul
的属性 justify-content:center
。
问题是 div
计算 ul
,因为它只有一列,即使我有多列。所以当它应该是 800px $ c $时,宽度 ul
200px
c>。因此,当我将 justify-content:center
(或 flex-end
)的属性添加到 div
,它以 ul
为中心,好像只有 200px
你会注意到容器保持一个固定的宽度,能容纳一个列。包装列只是溢出它。此问题已在此处记录: 当flexbox项目以列方式打包时,容器不会增加其宽度
作为解决方案,您可以:
- 切换到
flex-direction:row
,它没有包含包装项目的问题( demo ) - 使用
display:flex
以外的其他语言,例如display:inline-block
- 使用Javascript / jQuery。这里有一个可能的解决方法: http://stackoverflow.com/a/26231447/3597276
I have an li
of 15 items displaying as flex-direction: column
(it's applied to the parent (ul
)). I then have a div
wrapping the ul
with the property of justify-content: center
.
The problem is, the div
calculates the ul
as if it's only one column, even though I have multiple columns. So the width of the is ul
200px
when it should be 800px
. Therefore, when I add the property of justify-content: center
(or flex-end
) to the div
, it centers the ul
as if it's only 200px
, so it doesn't center properly.
How can I fix it?
div {
background-color: aqua;
height: 700px;
display: flex;
justify-content: center;
}
ul {
display: flex;
align-items: center;
flex-wrap: wrap;
flex-direction: column;
}
li {
outline: 1px solid;
background-color: greenYellow;
list-style-type: none;
width: 200px;
height: 150px;
}
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
</ul>
</div>
The obstacle you have encountered is a fundamental deficiency in flex layout:
A flex container in column-direction will not expand along with its wrapping items.
This problem can be illustrated by wrapping a border around the ul
:
You'll notice that the container keeps a fixed width, able to accommodate a single column. Wrapping columns simply overflow it. This problem has been documented here: When flexbox items wrap in column mode, container does not grow its width
As a solution you can:
- switch to
flex-direction: row
, which has no problem containing wrapping items (demo) - use something other than
display: flex
, such asdisplay: inline-block
- Use Javascript/jQuery. Here's one possible fix: http://stackoverflow.com/a/26231447/3597276
这篇关于Flex容器计算一列,当有多列时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!