CSS-垂直居中的几种方法

1.将div设置为表格,然后再使用table的vertical-align属性设置为middle;

 #cell{
        display: table;/*table-cell*//*inline-block*/
        vertical-align: middle;
        background-color: green;
         100px;
        height: 100px;
      }

此方法可以动态改变div内容高度,当高度不够时,内容不会被截断,自动撑大空间;

2.这个方法使用绝对定位的 div,把它的 top 设置为 50%,top margin 设置为负的 content 高度的一半。这意味着对象必须在 CSS 中指定固定的高度。

因为有固定高度,如果给 content 指定 overflow:auto,此时 content 太多的话,就会出现滚动条,以免content 溢出,没有足够空间时,content 会消失(类似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的情况)

content {
           position:absolute;
           top:50%;
           height:240px; 
           margin-top:-120px; /* negative half of the height */ 
         }

3.在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight的一半;没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现。
content 清除浮动,并显示在中间:

floater {
  float:left; height:50%; 
  margin-bottom:-120px;
}
#content {
  clear:both;
  height:240px; 
  position:relative;
}

4.使用一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的;无足够空间时,content 被截断,但是不会有滚动条出现

#cell{
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        height: 240px;
         50%;
        background-color: gray;
      }

5.这个方法只能将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了;无足够空间时不会被截断;只对文本有效(块级元素无效) ;多行时,断词比较糟糕;这个方法在小元素上非常有用,例如使按钮文本或者单行文本居中。

content {
      height:100px; 
      line-height:100px;     }

http://www.qianduan.net/css-to-achieve-the-vertical-center-of-the-five-kinds-of-methods/

原文地址:https://www.cnblogs.com/Decmber/p/4926070.html