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

2021-03-03  本文已影响0人  无言_4f45
  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;
  }
上一篇下一篇

猜你喜欢

热点阅读