简体   繁体   English

如何垂直居中一个字体真棒图标?

[英]How to vertically center a font-awesome icon?

In the following example, I would like to center the fa-plus icon inside the circle. 在下面的示例中,我想将fa-plus图标置于圆圈内。

在此输入图像描述

What I notice is the glyph is aligned with the top of the <i> tag. 我注意到的是字形与<i>标签的顶部对齐。 However I have added everything that should be needed to align it vertically: 但是我添加了垂直对齐所需的一切:

https://jsfiddle.net/x2n13p4e/2/ https://jsfiddle.net/x2n13p4e/2/

HTML: HTML:

<a class="btn icon-btn btn-success" href="#">
    <i class="btn-glyphicon text-success fa fa-plus"></i>
    Add
</a>

CSS: CSS:

.btn-glyphicon {
    padding: 3px;
    background: #ffffff;
    margin-right: 4px;
    border-radius: 50px;
    width: 1.5em;
    height: 1.5em;
    text-align: center;
    vertical-align:middle !important;
    align-items:center;
}

.icon-btn {
    padding: 1px 15px 3px 2px;
    border-radius: 50px;
    text-align: center;
    vertical-align:middle;
}

With position: relative , you make the icon a container for absolute positioned items inside of it or for pseudo classes, like :before or :after . 使用position: relative ,可以使图标成为其内部绝对定位项的容器 伪类,如:before:after

A absolute positioned item inside of a relative positioned container can be centered horizontally and vertically as follows: 相对定位容器内的绝对定位项可以水平和垂直居中,如下所示:

.center-horizontally-and-vertically {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

how-to-center-an-element-horizontally-and-vertically 如何到中心-AN-元件水平-和-垂直

Example

 .btn-glyphicon { position: relative; padding: 3px; background: #ffffff; margin-right: 4px; border-radius: 50px; width: 1.5em; height: 1.5em; text-align: center; vertical-align: middle !important; align-items: center; } .btn-glyphicon:before { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .icon-btn { padding: 1px 15px 3px 2px; border-radius: 50px; text-align: center; vertical-align: middle; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <a class="btn icon-btn btn-success" href="#"> <i class="btn-glyphicon text-success fa fa-plus"></i> Add </a> 

JSFiddle 的jsfiddle

Instead of 代替

width: 1.5em;
height: 1.5em;

try it with: 试试看:

width: 0 auto;
padding: 5px;

https://jsfiddle.net/RezaScript/Lz615auc/2/ https://jsfiddle.net/RezaScript/Lz615auc/2/

Try to use line-height property in .btn-glyphicon class. 尝试在.btn-glyphicon类中使用line-height属性。

.btn-glyphicon {
  padding: 3px;
  background: #ffffff;
  margin-right: 4px;
  border-radius: 50px;
  width: 1.5em;
  height: 1.5em;
  line-height: 1.5em;
  text-align: center;
  vertical-align:middle !important;
  align-items:center;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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