图标文字对齐在平时的工做中是最多见的了,最先学习时候通常都是用vertical-align,可是因为inline-block元素在和文字对齐时候的一些很麻烦的表现(见上一篇文章),你们应该都经历过那种行框高度高出几px的情形。简单暴力的话还能够用absolute定位方法。flex布局出现之后不少时候用flex的居中对齐也是很方便的。web
下面就以实现下面这个按钮的样式总结下几种方法:布局
.btn { display: inline-block; padding: 6px 12px; font-size: 14px; line-height: 20px; text-align: center; white-space: nowrap; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background: #fff; border: 1px solid #ccc; border-radius: 4px; } .btn:hover, .btn:focus { color: #333; background-color: #e6e6e6; border-color: #8c8c8c; } <button class="btn"><i class="icon icon-info"></i> warning</button>
思路很简单,要让图标和文字对齐,就让i
元素高度和和文字行高一致而且是对齐,而后图标背景居中就能够了,问题在于inline-block
元素内没有内联元素则其基线是margin
底边缘,这样和文字对齐时候就会有上下交错致使行框的高度都增高了,既然这样咱们只要让i
元素基线和文字基线一致就能保证和文字对齐了,方案就是在其中包含文字同时文字又不显示出来:学习
.icon { display: inline-block; width: 20px; height: 20px; //等于行高 text-indent: -9999em; //隐藏文字 white-space: nowrap; } .icon::before { content: 'icon'; } .icon-info { background: url(./info-circle.png) no-repeat center; }
用元素插入文字,用一个很大的text-indent
来隐藏文字就能够达到想要的效果了。flex
说到绝对定位的方法你们确定都会了,给button
元素设置relative
,而后图标绝对定位:url
.btn { ... position: relative; padding-left: 32px; } .icon { position: absolute; width: 20px; height: 20px; left: 12px; }
若是上层元素没有影响absolute
的定位,其实能够省去button
的相对定位,直接使用无依赖绝对定位便可,用margin-left
调整位置:spa
.btn { ... padding-left: 32px; } .icon { position: absolute; width: 20px; height: 20px; margin-left: -20px; }
这个直接给button设置display:inline-flex;align-items: center;
便可。code
关于使用哪种方法都是能够选择的,可是第一种方法但愿你们能够认真去思考下能收获不少关于内联元素对齐的知识。blog