CSS将文本垂直对齐中间/中心

时间:2013-08-21 19:10:48

标签: css3

我知道这听起来很简单,但它对我不起作用。我做错了什么?

.popuphdr {
      background-color:#00477f;
      height:30px;
      width:100%;
      margin:0px;
      color: #ffffff;
      vertical-align:middle;
}


<div class="popuphdr">
        <div>WARNING - Read carefully before proceeding</div>   
</div>

3 个答案:

答案 0 :(得分:2)

vertical-align: middle不适用于div元素(不会产生您正在寻找的影响)

有关可能的解决方案,请参阅http://www.vanseodesign.com/css/vertical-centering/,您可以通过几种方式来完成您想要完成的任务。

-

从该页面获取这里的css是简单的解决方案:

.popuphdr {
    display: table;
    /* Your other CSS HERE as well, minus vertial-align */
 }

.popuphdr div {
    display: table-cell;
    vertical-align: middle;
}

这是一个扩展的jsfiddle,你的js和添加文本对齐中心:

http://jsfiddle.net/BqgVM/1/

答案 1 :(得分:0)

我是绝对居中的粉丝(也在crowebird发布的链接中指出)。它运作良好而且很简单。

More details here

HTML

    <div class="popuphdr">
        <div>WARNING - Read carefully before proceeding</div>   
</div>

CSS

.popuphdr {
    background-color:#00477f;
    height:30px;
    width:100%;
    color: #ffffff;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

And a working Fiddle here

答案 2 :(得分:0)

.popuphdr{
    display: -webkit-flexbox;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;

    background-color:#00477f;
    height:30px;
    width:100%;
    margin:0px;
    color: #ffffff;
}

CSS Flexbox太棒了。以下是一些链接,可以了解更多信息:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/ http://coding.smashingmagazine.com/2013/05/22/centering-elements-with-flexbox/