CSS-垂直居中

主体部分

<div class="out">
    <div class="in"></div>
</div>

 

第一种 flex布局 (我觉得是最简单的一种)

<style type="text/css">
        .out{
            width: 200px;
            height: 150px;
            background: #42B983;
            display: flex;
        }
    .in{
            background: #7E7E7E;
            width: 50px;
            height: 50px;
            margin: auto;
        }            
</style>
第二种
.out{
            width: 200px;
            height: 150px;
            background: #42B983;
            display: flex;
            align-items: center;/* y轴居中 */
            /* justify-content: center;//X轴居中 */
        }
  .in{
            background: #7E7E7E;
            width: 50px;
            height: 50px;
      }
第三种
.out{
    width: 200px;
    height: 150px;
    background: #42B983;
    display: flex;
    }
.in{
    background: #7E7E7E;
    width: 50px;
    height: 50px;
    align-self: center;//子项在Y轴的对齐方式
    }
第四种  相对定位
.out{
     width: 200px;
     height: 150px;
     background: #42B983;
        }
.in{
    background: #7E7E7E;
    width: 50px;
    height: 50px;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
     /* //水平居中
     left: 50%;
     transform: translate(-50%,-50%); */
  }

 

第五种 绝对定位
.out{
            width: 200px;
            height: 150px;
            background: #42B983;
            position: relative;
        }
        .in{
            background: #7E7E7E;
            width: 50px;
            height: 50px;
            position: absolute;
            top: 0;
            bottom: 0;
            margin: auto;
            /* //水平居中
            left: 0;
            right: 0; */
        }

 

posted @ 2020-10-22 16:09  小令君  阅读(75)  评论(0编辑  收藏  举报