Tobias J. Tobias J. - 17 days ago 11
CSS Question

How to center FontAwesome icon in css before content vertically

I am going crazy. I have read dozens of blog articles and different stackoverflow postings but I am unable to vertically center a FontAwesome icon which is placed as content inside a css before pseudo element of a link element.

This is my CSS Code:

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;
}


And thats the HTML code:

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


Here you can find a fiddle which shows my problem: https://jsfiddle.net/r1vysfaf/1

UPDATE:

I want to avoid using javascript to solve the styling issue. Furthermore the text of the link is dynamic and therefore it is not a solution to use "constant magic" spacings for paddings/margin/top.

Answer

Use display: table for parent and table-cell for child and alter your css as following:

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>