【问题标题】:Centering an "i" element in a div在 div 中将“i”元素居中
【发布时间】:2015-02-06 02:20:24
【问题描述】:

谁能想到一个更好的方法来将这个“i”元素居中到这个 div 中,而不像我在这里所做的那样使用像素特定的边距。 这是必要的,因为“i”元素所在的 div 在悬停在它上面时会增长。

这是我的代码。

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

【问题讨论】:

  • 为什么斜体字没有任何文字?
  • 本例中的“i”标签用于实现“font awesome”图标。看看:fortawesome.github.io/Font-Awesome
  • 呃。这是对标记的令人反感的滥用。
  • 哈哈,这还不是最糟糕的.....如果代码有效......没问题?

标签: javascript jquery html css center


【解决方案1】:

查看下面的输出

  • 将 text-align: center 和 line-height:50px 添加到 div

  • 从i中移除绝对位置

  • 移除#bars 样式

  • 将 line-height:60px 添加到悬停状态,因为那里的高度发生变化

.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>

【讨论】:

  • 很好的解决方案!结合你和chipChocolate.py所说的话,我得到了我想要的
【解决方案2】:

使用transform: scale(1.4) 而不是更改widthheight

.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>

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 2023-03-29
    • 2021-08-13
    • 2017-07-12
    • 2023-01-24
    • 2012-11-15
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多