多行文本垂直居中

Avatar of Chris Coyier
Chris Coyier 发布

DigitalOcean 为您旅程的每个阶段提供云产品。 立即开始使用 200 美元的免费额度!

如果您只有一行文本或一个单词,则可以使用一种巧妙的方法通过 CSS 将其在块级元素中垂直居中。 将该文本的 **line-height** 设置为等于该框的 **height**。 效果很好,但如果该文本需要换行,则会失败。

“气泡” 是一个经典的示例,我们可能希望文本在水平和垂直方向上都居中,并且能够适应多行。 使用 CSS 表格有一个简单的小 CSS 技巧可以实现这一点。 以下是结果

查看演示下载文件

HTML 代码很简单。“区域” 只是我们正在处理的区域,我们可以在其中设置 position: relative;,以便我们可以绝对定位气泡内的文本区域。

<div class="area">
      <div class="bubble">
          <p>To look best, text should really be centered inside this bubble both vertically and horizontally.</p>
      </div>
</div>

我们将“气泡” 设置为 display: table;,它本身并没有做太多事情,但随后我们可以将内部的 <p> 元素设置为 table-cell,**这允许我们对其使用 vertical-align 属性。**

.area { 
  width: 300px; 
  height: 300px; 
  background: url(../images/abe-bg.png) no-repeat; 
  position: relative;
}

.bubble { 
  position: absolute; 
  left: 93px; 
  top: 21px; 
  width: 135px; 
  height: 84px; 
  display: table; 
}

.bubble p {
  display: table-cell; 
  vertical-align: middle; 
  text-align: center; 
}

我认为这个技巧非常棒。 当前版本的 CSS-Tricks 在页脚处有一个小型的 Twitter 气泡,我用它实现了这一点。

IE <= 7 怎么办?

IE 8 支持 CSS 表格,但 IE 7 及更低版本不支持。 太可惜了。 相反,您会看到这个

… 情况可能更糟。 我希望 Dean Edwards 的 ie8.js 可以解决这个问题,但没有成功(至少目前还没有)。

更新 1

Boris Kuzmic 在下方评论了一个完美的解决方案,可以使 IE 6 和 7 完美工作

<!--[if lt IE 8]>
<style>
.bubble { position: absolute; left: 93px; top: 21px; width: 135px; height: 84px; text-align: center;}
.bubble p { position: relative; font-size: 11px;
margin-top: expression(this.offsetHeight < this.parentNode.offsetHeight ? parseInt((this.parentNode.offsetHeight - this.offsetHeight) / 2) + "px" : "0");
}
</style>
<![endif]-->

更新 2

Boris 再次提供了一种方法,可以防止 IE 表达式泄漏内存(这样它只需要评估一次,而不需要持续运行)。

.bubble p { position: relative; font-size: 11px;
margin-top: inherit;
*clear: expression(
style.marginTop = "" + (offsetHeight < parentNode.offsetHeight ? parseInt((parentNode.offsetHeight - offsetHeight) / 2) + "px" : "0"),
style.clear = "none", 0
);
}

更新 3

James John Malcolm 也提供了一种针对 IE 的技术。 它的语义性略差(需要一个额外的 div),但不需要表达式。

首先将内部的 <p> 包裹在一个新的 <div> 中,然后

<!--[if lt IE 8]>
<style>
.bubble div { position: absolute; top:50%;}
.bubble div p {position: relative; top: -50%}
</style>
<![endif]–>

更新 4

Andy Howard 的另一种方法。