如何在动态高度div中垂直居中文本? [英] How can I vertically center text in a dynamically height div?

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

问题描述

 < body> 
< div style =position:absolute; height:100%; width:100%;>
< h1 style =text-align:center;>文字< / h1>
< / div>
< / body>

如何在div标签内部垂直居中h1标签,无论div元素有多高是什么?即如果用户改变他的浏览器高度,我想让h1在中心垂直对齐,根据新的高度。



谢谢。

解决方案

我遇到的最好的解决方案是使用 display wrapper元素作为以允许在元素上使用 vertical-align:middle p>

查看此 工作小提示示例



HTML

 < body& 
< div>
< h1>文字< / h1>
< / div>
< / body>

CSS

  body {width:100%; height:100%;} / *这只是查看div高度... * / 

div {
position:absolute;高度:100%; width:100%;
display:table;
}
h1 {
display:table-cell;
vertical-align:middle;
text-align:center;
}






TESTED ON



Windows XP Profissionalversão2002 Service Pack 3




  • Explorer 8.0.6001.18702

  • Opera 11.62

  • Firefox 3.6.16

  • Safari 5.1.2

  • Google Chrome 18.0.1025.168 m



Windows 7 Home Edition Service Pack 1




  • Internet Explorer 9.0.8112.164211C

  • Opera 11.62


  • Safari 5.1.4

  • Google Chrome 18.0.1025.168 m



Linux Ubuntu 12.04




  • Firefox 12.0

  • Chromium 18.0.1025.151(开发人员版本130497 Linux)


<body>
    <div style="position:absolute; height:100%; width:100%;">
        <h1 style="text-align:center;">Text</h1>
    </div>
</body>

How can I vertically center the h1 tag inside of the div tag, no matter how tall the div element is? i.e. If the user changes his browser height, I want the h1 to vertically align in the center, according to the new height.

Thanks.

解决方案

The best solution I've ever encountered is to make use of the display property and set the wrapper element as a table to allow the usage of vertical-align:middle on the element to be centered:

See this working Fiddle Example!

HTML

<body>
    <div>
        <h1>Text</h1>
    </div>
</body>

CSS

body {width: 100%; height: 100%;}   /* this is just to "view" the div height...*/

div {
    position:absolute; height:100%; width:100%;
    display: table;
}
h1 {
    display: table-cell;
    vertical-align: middle;
    text-align:center;
}


TESTED ON

Windows XP Profissional versão 2002 Service Pack 3

  • Internet Explorer 8.0.6001.18702
  • Opera 11.62
  • Firefox 3.6.16
  • Safari 5.1.2
  • Google Chrome 18.0.1025.168 m

Windows 7 Home Edition Service Pack 1

  • Internet Explorer 9.0.8112.164211C
  • Opera 11.62
  • Firefox 12.0
  • Safari 5.1.4
  • Google Chrome 18.0.1025.168 m

Linux Ubuntu 12.04

  • Firefox 12.0
  • Chromium 18.0.1025.151 (Developer Build 130497 Linux)

这篇关于如何在动态高度div中垂直居中文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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