假设我有一个bootstrap按钮,带有一个字体很棒的图标和一些文本:

<div>
    <i class='icon icon-2x icon-camera'></i>
    hello world
</div>

我如何使文本显示垂直居中? 文本现在与图标的底部边缘对齐:http://jsfiddle.net/V7DLm/1/


当前回答

一个flexbox选项-字体awesome 4.7及以下

足总4。x托管URL - https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css

div { display: inline-flex; /* make element size relative to content */ align-items: center; /* vertical alignment of items */ line-height: 40px; /* vertically size by height, line-height or padding */ padding: 0px 10px; /* horizontal with padding-l/r */ border: 1px solid #ccc; } /* unnecessary styling below, ignore */ body {display: flex;justify-content: center;align-items: center;height: 100vh;}div i {margin-right: 10px;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(34, 100%, 52%, 0.5);cursor: pointer;} <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <div> <i class='fa fa-2x fa-camera'></i> hello world </div>

小提琴

http://jsfiddle.net/Hastig/V7DLm/180/


使用flex和字体很棒

足总5。x托管URL - https://use.fontawesome.com/releases/v5.0.8/js/all.js

div { display: inline-flex; /* make element size relative to content */ align-items: center; /* vertical alignment of items */ padding: 3px 10px; /* horizontal vertical position with padding */ border: 1px solid #ccc; } .svg-inline--fa { /* target all FA icons */ padding-right: 10px; } .icon-camera .svg-inline--fa { /* target specific icon */ font-size: 50px; } /* unnecessary styling below, ignore */ body {display: flex;justify-content: center;align-items: center;height: 100vh; flex-direction: column;}div{margin: 10px 0;}div {background-color: hsla(0, 0%, 87%, 0.5);}div:hover {background-color: hsla(212, 100%, 63%, 1);cursor: pointer;} <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script> <div class="icon-camera"> <i class='fas fa-camera'></i> hello world </div> <div class="icon-clock"> <i class='fas fa-clock'></i> hello world </div>

小提琴

https://jsfiddle.net/3bpjvof2/

其他回答

这对我来说很有效。

i.fa {
  line-height: 100%;
}

最简单的方法是设置垂直对齐css属性为middle

i.fa {
    vertical-align: middle;
}

如果没有对齐,一个简单的line-height: inherit;通过CSS在特定的i.a a元素有对齐问题可以做的伎俩足够简单。

你也可以使用全局解决方案,由于CSS的特异性略高,它将覆盖FontAwesome的.fa规则,该规则指定line-height: 1而不需要属性上的!important:

i.fa {
  line-height: inherit;
}

只要确保上面的全局解决方案不会在你可能使用fontaweesome图标的地方引起任何其他问题。

简单地定义图标元素的垂直对齐属性:

div .icon {
   vertical-align: middle;
}

这个问题几年前就有人问过了。我认为技术已经发生了很大的变化,浏览器的兼容性也更好了。你可以使用垂直对齐,但我认为它的可伸缩性和可重用性较差。我建议使用flexbox方法。

下面是原始海报使用的相同示例,但使用了flexbox。它为单个元素设置样式。如果按钮大小因某种原因而改变,它将继续保持垂直和水平居中。

.button {
    border: 1px solid #ccc;
    height: 40px;
    margin: 60px;
    padding: 4px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

例如:JsFiddle