css里面让盒子居中的几种方法

145 阅读1分钟
* {
        margin: 0px;
        padding: 0px;
    }
    
    .item {
        width: 400px;
        height: 400px;
        border: 1px red solid;
    }
    
    .item1 {
        width: 100px;
        height: 100px;
        background-color: yellowgreen;
    }
    1.先给父元素一个相对定位,然后通过绝对定位给4个方向都为0;用margin自适应,实现居中  */
     .box {
        position: relative;
    }
    
    .box1 {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
    } 
    
     2.利用弹性盒子flex布局;flex布局,设置水平与竖直方向的内容居中。给父元素设置flex布局,justify-content是主轴水平对齐方式,
    给他一个居中的属性,align-items 是侧轴垂直对齐方式,给他设置居中的属性 注意flex布局一定是要给父元素设置 
            
    .box {
        display: flex;
        justify-content: center;
        align-items: center;
    } 
    
     3.利用display: table-cell;是把父元素变成表格单元格形式,
    vertical-align: middle这个属性会设置单元格框中的单元格内容的对齐方式  定义单元格元素垂直居中 
      .box {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    
    .box1 {
        display: inline-block;
            /* margin: 0 auto;}*/
     4.网格布局的方法 优点代码少 缺点 兼容性低 justify-self是水平居中  align-self是垂直居中  还有一种用margin auto的方法也可以居中
     5.在只知道父元素宽高和不确定子元素宽高的情况下居中,
    只需要保证leftright的百分数一样的25%就可以实现水平居中 ,保证topbottom的百分数25%一样就可以实现垂直居中。
    .box {
        position: relative;
    }
    
    .box1 {
        background: #00FFFF;
        position: absolute;
        left: 25%;
        right: 25%;
        top: 25%;
        bottom: 25%;}  
    .box {
        display: grid;
    }
    
    .box1 {
        /* align-self: center;
        justify-self: center; 
    
    margin: auto;
}
</style>


<div class="box item">
    <div class="box1 item1">

    </div>
</div>