如何垂直中对齐未知高度的浮动元素? [英] How to vertically middle-align floating elements of unknown heights?

查看:277
本文介绍了如何垂直中对齐未知高度的浮动元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个(水平)居中的外部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?

我最终做了外部div

I eventually made the outer div

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.

确切的规则说(强调我的):

The exact rules say (emphasis mine):



  1. 浮动框的外顶不得高于其包含块

  2. 外顶不得高于任何 block /CSS21/box.html#outer-edgerel =noreferrer>外顶的元素浮动框的顶部不得高于任何 line-box ,其中包含源文档中较早的
    元素生成的框。

  1. A floating box's outer top may not be higher than the top of its containing block.
  2. 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.
  3. 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.




尽管如此,的规则#4:

That said, you can take advantage of rule #4:


  • 将每个浮动块放在内置级元素,用于建立新的块格式化上下文 / 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆