nowox
nowox

Reputation: 29096

How to vertically center a font-awesome icon?

In the following example, I would like to center the fa-plus icon inside the circle.

enter image description here

What I notice is the glyph is aligned with the top of the <i> tag. However I have added everything that should be needed to align it vertically:

https://jsfiddle.net/x2n13p4e/2/

HTML:

<a class="btn icon-btn btn-success" href="#">
    <i class="btn-glyphicon text-success fa fa-plus"></i>
    Add
</a>

CSS:

.btn-glyphicon {
    padding: 3px;
    background: #ffffff;
    margin-right: 4px;
    border-radius: 50px;
    width: 1.5em;
    height: 1.5em;
    text-align: center;
    vertical-align:middle !important;
    align-items:center;
}

.icon-btn {
    padding: 1px 15px 3px 2px;
    border-radius: 50px;
    text-align: center;
    vertical-align:middle;
}

Upvotes: 2

Views: 9183

Answers (3)

user3589620
user3589620

Reputation:

With position: relative, you make the icon a container for absolute positioned items inside of it or for pseudo classes, like :before or :after.

A absolute positioned item inside of a relative positioned container can be centered horizontally and vertically as follows:

.center-horizontally-and-vertically {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

how-to-center-an-element-horizontally-and-vertically

Example

.btn-glyphicon {
  position: relative;
  padding: 3px;
  background: #ffffff;
  margin-right: 4px;
  border-radius: 50px;
  width: 1.5em;
  height: 1.5em;
  text-align: center;
  vertical-align: middle !important;
  align-items: center;
}

.btn-glyphicon:before {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.icon-btn {
  padding: 1px 15px 3px 2px;
  border-radius: 50px;
  text-align: center;
  vertical-align: middle;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<a class="btn icon-btn btn-success" href="#">
  <i class="btn-glyphicon text-success fa fa-plus"></i> Add
</a>

JSFiddle

Upvotes: 3

OM Tiwari
OM Tiwari

Reputation: 79

Try to use line-height property in .btn-glyphicon class.

.btn-glyphicon {
  padding: 3px;
  background: #ffffff;
  margin-right: 4px;
  border-radius: 50px;
  width: 1.5em;
  height: 1.5em;
  line-height: 1.5em;
  text-align: center;
  vertical-align:middle !important;
  align-items:center;
}

Upvotes: 0

Reza Saadati
Reza Saadati

Reputation: 5419

Instead of

width: 1.5em;
height: 1.5em;

try it with:

width: 0 auto;
padding: 5px;

https://jsfiddle.net/RezaScript/Lz615auc/2/

Upvotes: 1

Related Questions