Home  >  Article  >  Web Front-end  >  How to Vertically Center Floating Elements of Unknown Heights?

How to Vertically Center Floating Elements of Unknown Heights?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 04:18:02153browse

How to Vertically Center Floating Elements of Unknown Heights?

Vertically Middle-Aligning Floating Elements of Unknown Heights

Problem:

You have a container element that horizontally centers two floating elements of varying heights. By default, these floats align to the top of the container. How can you vertically center them?

Answer:

Direct vertical alignment of floats is not possible, as they adhere to specific alignment rules that prioritize alignment to the top. However, you can achieve this effect by exploiting the rule that floats can be contained within elements that establish a new block formatting context (BFC).

Solution:

  1. Wrap each float in an inline-level element with display: inline-block. This creates a BFC around the float and allows for vertical alignment.
  2. Use vertical-align to align the inline-block wrappers vertically.
  3. Ensure that the wrappers have sufficient width to accommodate their contents, as otherwise space may appear between them.

Example:

<code class="css">.float-left {
  float: left;
}

.float-right {
  float: right;
}

#main {
  border: 1px solid blue;
  margin: 0 auto;
  width: 500px;
}

/* Float wrappers */
#main > div {
  display: inline-block;
  vertical-align: middle;
  width: 50%;
}</code>
<code class="html"><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></code>

The above is the detailed content of How to Vertically Center Floating Elements of Unknown Heights?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn