码迷,mamicode.com
首页 > 其他好文 > 详细

图片文字水平居中

时间:2016-02-16 10:04:20      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

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

图片文字水平居中

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!