美文网首页
CSS水平垂直居中布局的常用方法

CSS水平垂直居中布局的常用方法

作者: 无言_4f45 | 来源:发表于2021-03-03 20:50 被阅读0次
    1. 已知宽高的情况下
    div{
                width: 200px;
                height: 200px;
                background: green;
               //方法一
                position: absolute;
                left: 0;
                right: 0;
                bottom: 0;
                top: 0;
                margin: auto;
                //方法二
                position: absolute;
                left: 50%;/*定位父容器的50%*/
                top: 50%;
                margin-left: -100px;
                margin-right: -100px;
               
            }
    

    2.宽高未知的情况下,使用绝对定位transform

                position: absolute;
                left: 50%;/*定位父容器的50%*/
                top: 50%;
                transform: translate(-50%,-50%);
    

    3.flex弹性布局

                /*父容器设置为flex*/
                display: flex;
                width: 100%;
                height: 100vh;
                justify-content: center;
                align-items: center;
    

    4.table布局

    .wrap{
        width: 100%;
        height: 100vh;
        display: table;
      }
      .item {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
      }
    

    相关文章

      网友评论

          本文标题:CSS水平垂直居中布局的常用方法

          本文链接:https://www.haomeiwen.com/subject/zrdqqltx.html