如何垂直中对齐未知高度的浮动元素? [英] How to vertically middle-align floating elements of unknown heights?
问题描述
我有一个(水平)居中的外部div,包含两个未知宽度的元素:
I have a (horizontally) centered outer div containing two elements of unknown width:
<div style='width:800px; margin:0 auto'>
<div style='float:left'>...</div>
<div style='float:right'>...</div>
</div>
默认情况下,两个浮点数都是顶部对齐的,并且具有不同的/未知的和不同的高度。有没有办法使它们垂直居中?
Both floats are top-aligned by default, and are of varying/unknown and different heights. Is there any way to make them vertically centered?
我最终做出了外部
display: table
和内部divs
display: table-cell;
vertical-align: middle;
text-align: left/right;
但我只是好奇,如果有一个方法来做这个漂浮。
but I'm just curious if there's a way to do this with the floats.
推荐答案
您不能直接执行此操作,因为 float 与顶部对齐:
You can't do this directly, because floats are aligned to the top:
如果有一个线框,浮动框与当前行框的顶部对齐
。
If there is a line box, the outer top of the floated box is aligned with the top of the current line box.
确切规则说(强调我的):
- 浮动框的外顶部不得高于其包含块的顶部。
- 浮动框的外顶部可能不是高于任何阻止或浮动广告框在源文档中较早生成的
元素。 - 元素的浮动框的a href =https://www.w3.org/TR/CSS21/box.html#outer-edge>外顶部可能不会高于任何,其中包含由源文档中较早的
元素生成的框。 / li>
- A floating box's outer top may not be higher than the top of its containing block.
- The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.
- The outer top of an element's floating box may not be higher than the top of any line-box containing a box generated by an element earlier in the source document.
- strong>浮动框必须尽可能高。
- A floating box must be placed as high as possible.
,您可以利用规则#4:
That said, you can take advantage of rule #4:
- 将每个浮动块放在inline-level 元素,用于建立新的块格式化上下文 / BFC),例如
display:inline-block
。 - 这些包装器将包含浮动,因为它们建立了一个BFC,因为它们是内联级。
- 使用
vertical-align
垂直对齐这些包装。
- Place each float inside inline-level elements that establish a new block formatting context /BFC), e.g.
display: inline-block
. - These wrappers will contain the floats because they establish a BFC, and will be one next to the other because they are inline-level.
- Use
vertical-align
to align these wrapper vertically.
在内联块封装器之间可能会出现一些空间。请参见如何删除inline-block元素之间的空格?以修复它。
Be aware that some space might appear between the inline-block wrappers. See How to remove the space between inline-block elements? to fix it.
#main {
width: 500px;
margin: 0 auto;
border: 1px solid blue;
}
#main > div { /* Float wrappers */
display: inline-block;
vertical-align: middle;
width: 50%;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
<div id="main">
<div>
<div class="float-left">
<p>AAA</p>
</div>
</div><div>
<div class="float-right">
<p>BBB</p>
<p>BBB</p>
</div>
</div>
</div>
这篇关于如何垂直中对齐未知高度的浮动元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!