一、 负外边居中

/*省略了尺寸的设置,侧重了重点,读者可以把部分内容加上*/
.main{/*父元素*/
  position: relative;
}
.child{/*子元素*/
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: /*负的自身宽度一半*/
    margin-top: /*负的自身高度一半*/
}

二、 绝对定位居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
  <style type="text/css">
    .main{
      width: 400px;
      height: 400px;
      background-color: #aaa;
      position: relative;
    }
    .child{
      width: 200px;
      height: 200px;
      background-color: rgb(39,40,34);
      position: absolute;
      margin: auto;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
  </style>
</head>
<body>
    <div class="main">
      <div class="child"></div>
    </div>
</body>
</html>

三、flex属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>flex居中定位</title>
    <style>
        html,body{
            background-color: #fefefe;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #app{
            width: 400px;
        }
    </style>
</head>
<body>
        <div id="app">
        <p>Lorem ipsum dolor sit amet.</p>
    </div>
</body>
</html>

四、css3 属性transform

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>css3transform居中</title>
    <style>
        html,body{
            background-color: #ccc;
            margin: 0;
            padding: 0;
        }
        /*
        1,transform居中方法,不用指定具体width,height;
        2,使用transform属性进行居中定位
         */
        #app{
            border: 1px solid #c00;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
    </style>
</head>
<body>
    <div id="app">
        <p>Lorem ipsum dolor sit amet.</p>
    </div>
</body>
</html>

五、单行文本的垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Test</title>
  <style type="text/css">
    .block{
      height: 80px;
      background-color: blue;
      line-height: 80px;/*值与父元素高度相等*/
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="block">单行文本垂直居中</div>
</body>
</html>

六、img的垂直水平居中

使用到的重要样式属性display,vertical-align vertical-align:middle这个属性是对table元素垂直居中起作用,如果想使用在 img 元素上,就注意下面的 display 设置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
  <style type="text/css">
    .main{
      width: 400px;
      height: 400px;
      background-color: #aaa;
      display: table;/*父元素设置表格属性*/
      text-align: center;
    }
    .main span{
      display: table-cell;/*img设置成表格元素属性*/
      vertical-align: middle;/*两个display设置后这个属性就起作用*/
    }
  </style>
</head>
<body>
    <div class="main">
      <span><img src="1.jpg" alt="/" width="150px"></span>
    </div>
</body>
</html>

注意:

  • display:table-cell,这是对类似文字元素起作用的,所以包含在span标签内
  • 对于文字居中 h1, span, p 等类似文字标签都可以这样设置居中