垂直对齐:Flexbox VS表/表单元格上未知高度的元素 [英] Vertical align: Flexbox VS Table/Table-cell on elements with unknown height
问题描述
我在CMS内建立网站。有很多元素需要垂直居中的内容。但是,由于我没有最终内容(以及任何内容可以,将来会改变),我不能为这些容器设置固定的高度。
I'm building a website within a CMS. There are quite a few elements that require vertically centered content. However, since I don't have the final content (and whatever content can and will be change in the future) I cannot set a fixed height to those containers.
我只是花了好几分钟,试图找出为什么我的元素不会垂直对齐使用flexbox ...直到我发现它是缺乏一个固定的高度。
I just spent a good few minutes trying to figure out why my elements won't vertically align using flexbox...until I found out it's for the lack of a fixed height.
在过去,我使用display:table / table-cell组合来构建这样的布局。我最近开始使用flexbox模型越来越多,真的开始喜欢这些,而宁愿停止使用table / table-cell。
In the past I built such layouts using the display:table/table-cell combination. I started using flexbox models more and more lately and really start to like those and would rather stop using table/table-cell.
现在我不知道如何
推荐答案
如果你的flex容器 flex-direction:row
(默认方向),垂直居中可以使用的内容:
If your flex container is flex-direction: row
(the default orientation), to vertically center content you can use:
align-items: center; /* for a single line of flex items */
align-content: center; /* for multiple lines of flex items */
如果您的flex容器 flex-direction:column
,垂直居中的内容您可以使用:
If your flex container is flex-direction: column
, to vertically center content you can use:
justify-content: center;
这些方法无需定义任何高度。
These methods work without the need to define any heights.
有关详情,插图和现场演示,请参阅我的答案: http://stackoverflow.com/a/33049198/3597276
For more details, illustrations, and live demos, see my answer here: http://stackoverflow.com/a/33049198/3597276
从此回答:
下面是两个一般的中心解决方案。一个用于垂直对齐的flex项目(
flex-direction:column
),另一个用于水平对齐的flex项目(flex-direction:row
)。在这两种情况下,中心div的高度可以是可变的,未定义的,未知的,无论什么。中心div的高度无关紧要。
Below are two general centering solutions. One for vertically aligned flex items (
flex-direction: column
) and the other for horizontally aligned flex items (flex-direction: row
). In both cases the height of the centered divs can be variable, undefined, unknown, whatever. The height of the centered divs doesn't matter.
这篇关于垂直对齐:Flexbox VS表/表单元格上未知高度的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!