美文网首页Web前端之路
div水平居中,垂直居中的几种方式

div水平居中,垂直居中的几种方式

作者: wenronnie | 来源:发表于2020-05-31 16:51 被阅读0次

假设我们现在要实现box元素的居中

<div class="wp">
     <div class="box">123</div>
</div>
/* 公共代码 */
.wp {
    border: 1px solid red;
    width: 300px;
    height: 300px;
}
.box {
    background: green;    
}
.box.size{
    width: 100px;
    height: 100px;
}
/* 公共代码 */

1.box确定宽高

<div class="wp">
   <div class="box size">fff</div>
</div>

1.1absolute + 负margin

/* 定位代码 */
.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

1.2absolute + margin auto

.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

1.3absolute + calc

.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}

2.box不确定宽高

<div class="wp">
    <div class="box">123</div>
</div>

2.1absolute + transform

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

2.2.flex布局

.wp {
    display: flex;
    justify-content: center;
    align-items: center;
}

2.3table-cell

.wp {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

2.4lineheight

.wp {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.box {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
    text-align: left;
}

相关文章

网友评论

    本文标题:div水平居中,垂直居中的几种方式

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