css水平垂直居中的方法

如果div给定了固定宽高:

1.绝对定位+margin

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

2.margin+calc

.div {
    margin-left: auto;
    margin-right: auto;
    margin-top: calc((100% - 100px) / 2);
}

 

如果div没有指定宽高:

1.css-table+text-align+vertical-align

.outerDiv {
    border: 1px solid black;
    width: 300px;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}    

.div {
    display: inline-block;
}

2.line-height+text-align+vertical-align

.outerDiv {
    border: 1px solid black;
    width: 300px;
    height: 300px;
    line-height: 300px;
    text-align: center;
}    

.div {
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
}

 

万能方法

1.绝对定位+transform

.div {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%)  
}

2.flex+justify-center+align-items

.outerDiv {
    border: 1px solid black;
    width: 300px;
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
}    

.div {}

3.grid+justify-sleft+align-self 

.outerDiv {
    border: 1px solid black;
    width: 300px;
    height: 300px;
    display: gird;
}    

.div {
    justify-self: center;
    align-self: center;
}

 

posted @ 2022-02-23 18:09  南韵  阅读(47)  评论(0编辑  收藏  举报