简体   繁体   中英

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

See output Below

  • Add text-align: center and line-height:50px to div

  • remove absolute position from i

  • remove #bars style

  • Add line-height:60px to hover state as height changes there

 .nav-collapse { top: 30px; right: 30px; position: fixed; border-radius: 50%; width: 50px; height: 50px; line-height:50px; background-color: white; z-index:200; transition: line-height 2s, width 0.2s, height 0.2s; text-align:center; background:red; } .nav-collapse i{ color: #FFB361; } .nav-collapse:hover { width: 60px; height: 60px; line-height:60px; } 
 <div class="nav-collapse"> <i class="fa fa-bars fa-2x" id="bars">aa</i> </div> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM