Search code examples
javascriptjqueryhtmlcsscenter

Centering an "i" element in a div


Can anyone think of a better way to center this "i" element into this div, without using pixel specific margins as I have done here. It will be necessary, as the div the "i" element is in grows when hovering over it.

here is my code.

HTML:

<div class="nav-collapse">
  <i class="fa fa-bars fa-2x" id="bars"></i>
</div>

CSS:

.nav-collapse {
top: 30px;
right: 30px;
position: fixed;
border-radius: 50%;
width: 50px;
height: 50px;
background-color: white;
z-index:200;
transition: width 0.2s, height 0.2s;

}

.nav-collapse i{
position: absolute;
color: #FFB361;
}

#bars {
margin-left: 11px;
margin-top: 9px;
}


.nav-collapse:hover {
    width: 60px;
    height: 60px;
}

Solution

  • Use transform: scale(1.4) instead of changing the width and height.

    .nav-collapse {
      top: 30px;
      right: 30px;
      position: fixed;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      background-color: white;
      z-index: 200;
      transition:  transform 0.2s;
    }
    .nav-collapse i {
      position: absolute;
      color: #FFB361;
    }
    #bars {
      margin-left: 11px;
      margin-top: 9px;
    }
    .nav-collapse:hover {
      -webkit-transform: scale(1.4);
      transform: scale(1.4);
      -webkit-transform-origin: 50% 50%;
      transform-origin: 50% 50%;
      cursor: pointer;
    }
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
    <div class="nav-collapse">
      <i class="fa fa-bars fa-2x" id="bars"></i>
    </div>