垂直水平居中的几种方式

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }

      /*越往下兼容性越不好*/
      .p1 {
        width: 500px;
        height: 500px;
        margin-bottom: 100px;
        background: rgb(89, 6, 243);
        border: 4px solid yellow;
        /* AAA主要设置的属性 */
        display: table-cell;
        text-align: center;
        vertical-align: middle;
      }
      .c1 {
        width: 400px;
        background: red;
        text-align: left;
        /*不用设置高度*/
        /* AAA主要设置的属性 */
        display: inline-block;
      }
      /*优点: 兼容性较好;
      缺点: 使用起来比较麻烦,margin不管用,*/
      /* ---------------------------------------------------------- */
      .p2 {
        width: 500px;
        height: 500px;
        margin-bottom: 100px;
        background: green;
        border: 4px solid yellow;
        /* AAA主要设置的属性 */
        position: relative;
      }
      .c2 {
        background: red;
        /* AAA主要设置的属性 */
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
      }
      /*优点: 居中元素不会对其它元素产生影响,比较灵活
        缺点: transform属于CSS3内容,兼容性存在一定问题,但现在一般公司pc端,手机端都可以使用css3属性了
        兼容性:
        注意: Internet Explorer 9 要求前缀 -ms- 版本,ie9以下不支持 */
      /* ---------------------------------------------------------- */
      .p3 {
        width: 500px;
        height: 500px;
        margin-bottom: 100px;
        background: green;
        border: 4px solid yellow;
        /* AAA主要设置的属性 */
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .c3 {
        background: red;
        width: 50%;
      }
      /*优点: 只设置parent元素,比较简洁
        缺点: pc端兼容性存在一些问题,根据公司情况使用,手机端可以随便用
        兼容性:
        注意: 现在的一般浏览器都支持,但ie浏览器只支持ie11及以上的版本,*/
    </style>
    <script></script>
  </head>

  <body>
    <div class="p1">
      <div class="c1">
        22211111111111顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多等等等等等等顶顶顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多
      </div>
    </div>

    <div class="p2">
      <div class="c2">
        等等等等等等顶顶顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多等等等等等等顶顶顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多
      </div>
    </div>

    <div class="p3">
      <div class="c3">
        等等等等等等顶顶顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多等等等等等等顶顶顶顶顶顶顶顶顶顶等等等等等等顶顶顶顶顶顶顶顶顶顶顶顶顶顶顶大大大多多多多多多多多多
      </div>
    </div>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41111677/article/details/108200947