图片文字水平居中(移动端)

这样一个需求,第三方联合登陆的头像和昵称整体水平居中,如图:

对于这样的需求,不能简单的对包含头像和昵称的div使用margin: 0 auto了,因为昵称的长度是未知的。

solution 1:利用行内元素的padding-left属性。把图片绝对定位到padding-left区域内,然后对外层div元素设置文字居中,对span元素设置line-height,让文字垂直居中

<div class="container">
    <span class="wrap">
        <img src="pic-7.png" class="icon" alt="">
    Username
    </span>
</div>
.container {
    height: 10rem;
    text-align: center;
    background: #819121;
}
.wrap {
    display: inline-block;
    position: relative;
    margin-top: 3rem;
    padding-left: 3rem;
    line-height: 2rem;
    background: #BB9391;
}
.icon {
    position: absolute;
    left: 0;
    top: 0;
    height: 2rem;
}

效果图:

solution 2:box布局居中,对div元素设置box-pack,span元素设置display: block,由于想偷懒,省略兼容模式写法

<div class="container">
    <img src="pic-7.png" class="icon" alt="">
    <span class="username">Username</span>
</div>
.container {
    display: -webkit-box;
    -webkit-box-pack: center;
    height: 10rem;
    background: #B2B2CD;
}
.icon {
    margin-top: 2rem;
    height: 2rem;
}
.username {
    display: block;
    margin-top: 2rem;
    padding-left: 1rem;
    line-height: 2rem;
}

效果图:

点评:solution 1会比较稳定,而solution 2易维护。

原文地址:https://www.cnblogs.com/hupan508/p/5191836.html