如何在垂直内容之前将 FontAwesome 图标居中 css

How to center FontAwesome icon in css before content vertically

我快疯了。我已经阅读了数十篇博客文章和不同的 Whosebug 帖子,但我无法将 FontAwesome 图标垂直居中,该图标作为内容放置在 link 元素的伪元素之前的 css 中。

这是我的CSS代码:

a.button {
    background-color: green;
    padding: 5px 10px;
    color: #ffffff;
    cursor: pointer;
    position: relative;
    display: inline-block;
}

a.button.forward {
    padding-right: 35px;
}

a.button.back {
    padding-left: 35px;
}

a.button.back:before {
    font-family: FontAwesome;
    content: "\f100";
    font-size: 1em;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 10px;
}

这就是 HTML 代码:

<a class="button back">back to<br/>whatever</a>

在这里你可以找到一个 fiddle 来说明我的问题:https://jsfiddle.net/r1vysfaf/1

更新:

我想避免使用 javascript 来解决样式问题。此外 link 的文本是动态的,因此对于 paddings/margin/top.

使用 "constant magic" 间距不是解决方案

对 parent 使用 display: table,对 child 使用 table-cell,并按如下方式更改 css:

a.button {
    background-color: green;
    padding: 5px 10px;
    color: #ffffff;
    cursor: pointer;
    position: relative;
    display: table;
}

a.button.forward {
    padding-right: 35px;
}

a.button.back {
    padding-left: 10px;
}

a.button.back:before {
  font-family: FontAwesome;
  content: "\f100";
  font-size: 1em;
  line-height: 1em;
  display: table-cell;
  vertical-align: middle;
  padding: 0 10px 0 0;
}
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
    <a class="button back">back to<br/>whatever</a>

更新

添加了前进按钮,加上以 em 为单位的位置值,因此增加或减少字体大小或元素不会偏移图标。

在伪元素上使用 relative 而不是 absolute

FIDDLE

片段

a.button {
  background-color: green;
  padding: 5px 10px;
  color: #ffffff;
  cursor: pointer;
  position: relative;
  display: inline-block;
}
a.button.forward {
  padding-right: 35px;
}
a.button.back {
  padding-left: 35px;
}
a.button.back:before {
  font-family: FontAwesome;
  content: "\f100";
  font-size: 1em;
  position: relative;
  top: .625em;
  bottom: 0;
  right: 1.25em;
}
a.button.forward:after {
  font-family: FontAwesome;
  content: "\f101";
  font-size: 1em;
  position: relative;
  top: -.5em;
  left: 1.25em;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'>
<a class="button back">Back to<br/>whatever</a>
<a class="button back" style='font-size: 1.5em'>Font-size is<br/>increased by 50%</a>
<a class="button forward">Next to<br/>whatever</a>
<a class="button forward" style='font-size: .5em'>Font-size is<br/>decreased by 50%</a>