CSS水平居中与垂直居中的总结

html-css013

CSS水平居中与垂直居中的总结,第1张

1. 设置 margin: 0 auto

单行文本垂直居中,通过设置行高为父元素高度(父元素高度已知)。

图片垂直居中,设置上下padding(父元素高估不设置)。

图片垂直居中,下边这种方法会有一定偏差(父元素高估不设置)。

图片垂直居中,图片作为背景。

1. 若元素是行内块级元素, 基本思想是使用display: inline-block, vertical-align: middle和一个伪元素让内容块处于容器中央。

行内元素可可以转换为inline-block实现居中。

利用vertical-align:middle和dispaly: table在高级版本的浏览器实现效果

布局div:

未添加样式的效果图:

添加CSS样式效果:

最终实现的效果:

在IE6 7 下的方案 :

/*IE6*/

*html .wrapper{position:absolutetop:50%width:100%text-align:centerdisplay:blockheight:auto}

*html .subwrap{position:relativetop:-50%text-align:center}

/*IE7 可以合并 但是为了更好说明 没有合并*/

*+html .wrapper{position:absolutetop:50%width:100%text-align:centerdisplay:blockheight:auto}

*+html .subwrap{position:relativetop:-50%text-align:center}

案例代码懂点君给您准备好了,查看如下代码:

<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8" />

  <title>懂点君</title>

  <style type="text/css">

      html, body, .wrap {

          position: relative

          height: 100%

      }

      .wrap div {

          position: absolute

          left: 50%

          top: 50%

          background-color: #39f

          transform: translate(-50%, -50%)

      }

  </style>

</head>

<body>

  <div class="wrap">

      <div>垂直居中</div>

  </div>

  <script type="text/javascript"></script>

</body>

</html>

效果如下: