css实现垂直居中

还可以参看文章:https://www.cnblogs.com/coco1s/p/4444383.html

https://www.cnblogs.com/coco1s/p/4444383.html

不需要知道子元素的尺寸:
方法一:单行文本居中===>line-height==height
方法二:父元素使用display:table和子元素使用display:table-cell属性来模拟表格,子元素设置vertical-align:middle(vertical-align属性只对行内元素起作用,块级元素不起作用))即可垂直居中
html代码:
<div id="box">
  <div id="child">我也是一段测试文本</div>
</div>
css代码:
#box {
   300px;
  height: 300px;
  background: #ddd;
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}
方法三:使用绝对定位和平移变换
html结构:
<div class="box">
  <span>垂直居中</span>
</div>
css代码:
.box span{
  position: absolute;
  top:50%;
  left:50%;
  50%;
/*这个50%是相对于父元素的宽度而言的*/
/*设置完据对定位以后,盒子自动变为块级元素,就可以设置宽高了*/
  transform:translate(-50%,-50%);
/*平移用到的50%是相对于元素本身的宽高而言的*/
  text-align: center;
}
这种方法有一个非常明显的好处就是不必提前知道被居中元素的尺寸了,因为transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。
方法四:使用flex布局
html代码:
<div id="box">
  <div id="child">
    程序员怎么才能保护好眼睛?
  </div>
</div>
css代码:
#box {
   300px;
  height: 300px;
  background: #ddd;
  display: flex;
  align-items: center; //垂直居中

  justify-centent:center;//水平居中
}
#child {
   300px;
  height: 100px;
  background: #8194AA;
  line-height: 100px;
}
方法五:使用vertical-align
html代码:
<div id="box">
  <div id="child">
    程序员怎么才能保护好眼睛?
  </div>
</div>
.box {
   300px;
  height: 300px;
  line-height:300px
  <!-- 垂直居中 -->
  margin-top: 20px;
  background-color: #BBBBBB;
}
.child {
  display: inline-block;/*既想vertical-align生效,又想设置子块的宽高*/
  50%;
  line-height: 20px/normal/100%(相对于字体大小而言); /*单独给子元素设置行高,覆盖父级元素的行高*/
  vertical-align: middle; /*基线居中对齐*/

}

需要知道子元素的宽高:
方法一:绝对定位加负边距
.box3{position:relative;}
.box3 span{
  position: absolute;
  100px;
  height: 50px;
  top:50%;
  left:50%;
  margin-left:-50px;
  margin-top:-25px;
  text-align: center;
}
方法二:绝对定位加0 :通过margin:auto和top,left,right,bottom都设置为0实现居中,很神奇吧。不过这里得确定内部元素的高度
.box4 span{
   50%;
  height: 50%;
  background: #000;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

原文地址:https://www.cnblogs.com/cui-ting/p/10619769.html