zoukankan      html  css  js  c++  java
  • 水平垂直居中方法(包含flex新版本和旧版本)

    页面中有一个灰色的块:宽高各400px,块中还有一个小的div颜色为粉色:宽高各为200px,如何让这个粉色的块在灰色的块中水平垂直居中呢?

      <div class="wrap">
        <div class="box"></div>
      </div>
        *{
          padding:0;
          margin:0;
        }
        .wrap{
           400px;
          height:400px;
          background: grey;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    1.父相子绝,子: top:0; left:0; right:0 ;bottom:0; margin: auto;

        *{
          padding:0;
          margin:0;
        }
        .wrap{
           400px;
          height:400px;
          background: grey;

          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;

          position: absolute;
          top:0;
          left:0;
          right:0;
          bottom:0;
          margin: auto;
        }

     2.父相子绝,子:top:50%, left:50%, margin-left:-100px; margin-top: -100px;(这个100px就是子元素的宽高的一半)

    
    
       .wrap{
           400px;
          height:400px;
          background: grey;

          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;

          position: absolute;
          top:50%;
          left:50%;
          margin-left: -100px;
          margin-top: -100px;
        }
     

    3.父相子绝,子: top:50%;  left:50%; transform:translate(-50%,-50%)

        .wrap{
           400px;
          height:400px;
          background: grey;
    
          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
    
          position: absolute;
          top:50%;
          left:50%;
          transform:translate(-50%,-50%)
        }

    4.flex新版本:父级: display: flex;  justify-content: center; align-items: center;

        .wrap{
           400px;
          height:400px;
          background: grey;
    
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    5.flex旧版本:display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center;

      .wrap{
           400px;
          height:400px;
          background: grey;
    
          display: -webkit-box;
          -webkit-box-pack: center;
          -webkit-box-align: center;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    以上方法亲测有效,

  • 相关阅读:
    (转)游戏设备的三大未来趋势
    (转)零基础学习 Hadoop 该如何下手?
    (转)如何系统地学习数据挖掘?
    (转)大数据最核心的价值是什么?
    (转)面向对象编程的弊端是什么?
    (转)处理器架构、指令集和汇编语言,三者有何关系?
    (转)游戏界人士如何看待《征途》这款游戏?
    (转)想从事游戏开发,1 年内能精通 C++ 吗,还需要学习什么?
    (转)数据库老兵:NewSQL才是未来
    (转)神舟飞船上的计算机使用什么操作系统,为什么是自研发不是 Linux?
  • 原文地址:https://www.cnblogs.com/yaya-003/p/12072212.html
Copyright © 2011-2022 走看看