CSS 居中方法

1、完美居中:绝对定位 +  transform,适用于元素宽高未知的大多数情况

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .parent {
      position: relative;
      height: 300px;
      width: 300px;
      background: #ddd;;
    }
    .child {
      position: absolute;
      height: 100px;
      width: 100px;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      background: #333;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="child"></div>
  </div>
</body>
</html>

2、完美居中:flex布局,需要兼容flex

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .parent {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
      width: 300px;
      background: #ddd;
    }
    .child {
      height: 100px;
      width: 100px;
      background: #333;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="child"></div>
  </div>
</body>
</html>

3、内联元素水平居中:text-align,适用于常规文档流中的内联元素(span、a、input等),也包括inline-block元素

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .parent {
      text-align: center;
      height: 300px;
      width: 300px;
      background: #ddd;
    }
    .child {
      height: 50px;
      width: 100px;
      background: #aaa;
    }
  </style>
</head>
<body>
  <div class="parent">
    <span class="child">span</span><br>
    <input type="text" class="child" value="input"><br>
    <div class="child" style="display: inline-block;">inline-block</div><br>
  </div>
</body>
</html>

转http://www.qdfuns.com/notes/40578/0c0a10c9b2f7ee8b85a3381b36411593.html
posted @ 2017-02-08 15:19  恩恩先生  阅读(190)  评论(0编辑  收藏  举报