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


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

对于这样的需求,不能简单的对包含头像和昵称的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易维护。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM