PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 17, 2022

[FIXED] How to vertically align font-awesome icons in a button?

 November 17, 2022     bootstrap-4, font-awesome, vertical-alignment     No comments   

Issue

My goal is to create a block button with a related icon. Since Bootstrap 4 does not natively support glyphicon anymore and I would prefer using fonts or SVG images over PNG images, I have chosen to use font-awesome v5.

My problem is that the icon is slightly above the text and does not want to center itself, no matter what I tried.

Several answers here on StackOverflow suggested using the vertical-align property [1][2], but this seems to be completely ignored by the icon. I suppose this is due to the fact that both questions were asked in 2013 and font-awesome has been updated since then.

I tried messign with flexboxes, but this ended up moving both the text and the icon. I also tried applying the align-middle class to the span, but it didn't work either.

Here is my code so far:

<div class="container">
  <p>
    <a class="btn btn-lg btn-primary btn-block" role="button">
      <span class="fas fa-music fa-lg float-left my-icon"></span> 
      <span class="my-text">Music</span>
    </a>
  </p>
</div>

JSFiddle Link

As you can see, the icon is still elevated over the text, and I have no idea how to align it vertically.


Solution

The float-left on the icon is throwing off the vertical alignment. If you want the icon aligned to the left, and the text centered, you can use flexbox and defined widths like this...

<a class="btn btn-lg btn-primary btn-block d-flex align-items-center px-0" role="button">
      <span class="w-25 fas fa-music fa-lg my-icon"></span> 
      <span class="w-50 my-text">Music</span>
      <span class="w-25"></span>
</a> 

If you want both icon and text centered it's much simpler. Just remove the float and add align-middle to the btn...

<a class="btn btn-lg btn-primary btn-block align-middle" role="button">
  <span class="fas fa-music fa-lg my-icon"></span> 
  <span class="my-text">Music</span>
</a>

Demo: https://www.codeply.com/go/iJV8uQDVVD



Answered By - Zim
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing