css – 如何垂直中对齐未知高度的浮动元素?

我有一个(水平)居中的外部div,包含两个未知宽度的元素:
<div style='width:800px; margin:0 auto'>
  <div style='float:left'>...</div>
  <div style='float:right'>...</div>
</div>

认情况下,两个浮点都是顶部对齐的,并且是不同的/未知的和不同的高度。有什么办法让他们垂直居中吗?

我最终做了外面的div

display: table

和内部div

display: table-cell;
vertical-align: middle;
text-align: left/right;

但我只是好奇,如果有一个方法来做到这一点与浮动。

解决方法

你不能直接这样做,因为 floats是对齐到顶部:

If there is a line Box,the outer top of the floated Box is aligned
with the top of the current line Box.

准确rules说(强调我):

  1. A floating Box’s 07002 may not be higher than the top of its 07003.
  2. The 07002 of a floating Box may not be higher than the outer top of any 07005 or 07006 Box generated by an
    element earlier in the source document.
  3. The 07002 of an element’s floating Box may not be higher than the top of any 07008 containing a Box generated by an
    element earlier in the source document.
  1. A floating Box must be placed as high as possible.

也就是说,你可以利用规则#4:

>将每个浮标置于建立新的block formatting context / BFC的inline-level元件内部,例如。 display:inline-block。
>这些包装器将包含浮动,因为它们建立一个BFC,并且将是一个相邻的,因为它们是内联级别的。
>使用vertical-align垂直对齐这些包装。

请注意,内联块封装器之间可能会出现一些空格。请参阅How to remove the space between inline-block elements?修复它。

#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>

相关文章

Css3如何实现鼠标移上变长特效?(图文+视频)
css3怎么实现鼠标悬停图片时缓慢变大效果?(图文+视频)
jquery如何实现点击网页回到顶部效果?(图文+视频)
css3边框阴影效果怎么做?(图文+视频)
css怎么实现圆角边框和圆形效果?(图文+视频教程)
Css3如何实现旋转移动动画特效