微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>

原文地址:https://www.jb51.cc/css/220301.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。