Search code examples
htmlcssbuttoniconsfont-awesome

How to center fontawesome icons in a div?


I centered 3 divs on the middle of the screen, each one has an icon from fontawesome, but some icons like the dice and the code are a bit offset, except for the smile. (I assume this happened because the smile is rounded just like the div, but I'm not sure) I wanted to know how I can make all the icons centered on their own divs. Codepen with the whole code: Smooth Buttons with Fontawesome Icons

Here's the HTML and CSS code:

body {
  background-color: #333;
  font-size: 1.5em;
  padding: 0;
}

.buttons {
  display: flex;
  gap: 25px;
  justify-content: center;
  align-items: center;
  text-align: center;
  line-height: 50px;
  vertical-align: bottom;
  float: center;
}

.button {
  padding 5px;
  color: black;
  height: 50px;
  width: 50px;
  border: 15px solid #2b2b2b;
  background-color: #2b2b2b;
  border-radius: 100%;
  transition: all ease-in-out 0.5s;
}
<div class="buttons">
  <div class="button"><i class="fa fa-dice fa-2xl"></i></div>
  <div class="button"><i class="fa fa-code fa-2xl"></i></div>
  <div class="button"><i class="fa fa-smile fa-2xl"></i></div>
</div>

I've already tried changing the margin, display type and text-align, but nothing worked.


Solution

  • You can add class fa-fw for a fixed width icons. Secondly, your font is too large for the circles, so it got offset from the center. I set size to 20px now it looks centered.

    body {
      background-color: #333;
      font-size: 1.5em;
      padding: 0;
    }
    
    .buttons {
      display: flex;
      gap: 25px;
      justify-content: center;
      align-items: center;
      text-align: center;
      line-height: 50px;
      vertical-align: bottom;
      float: center;
    }
    
    .button {
      padding 5px;
      font-size: 20px;
      color: black;
      height: 50px;
      width: 50px;
      border: 15px solid #2b2b2b;
      background-color: #2b2b2b;
      border-radius: 100%;
      transition: all ease-in-out 0.5s;
    }
    
    .button:hover {
      transform: scale(1.1) rotate(360deg);
      box-shadow: 0 0 15px #111;
      cursor: pointer
    }
    
    .button:active {
      animation: clicked ease 0.25s
    }
    
    @keyframes clicked {
      from {
        background-color: #2b2b2b;
        border: 15px solid #2b2b2b;
        scale: 1;
      }
      to {
        background-color: #333;
        border: 15px solid #333;
        scale: 1.05;
      }
    }
    <div class="buttons">
      <div class="button"><i class="fa fa-fw fa-dice fa-2xl"></i></div>
      <div class="button"><i class="fa fa-fw fa-code fa-2xl"></i></div>
      <div class="button"><i class="fa fa-fw fa-smile fa-2xl"></i></div>
    </div>
    
    <script src="https://kit.fontawesome.com/4fc295af45.js" crossorigin="anonymous"></script>