Bootstrap Glyphicons是如何工作的?

42

我了解一些 CSS 和 HTML 的基础知识,并且有时也会使用它们,但并不是专业的。我很好奇 Bootstrap Glyphicons 是如何工作的。我的意思是,在 Bootstrap 的压缩文件中没有图片文件,那这些图标从哪里来呢?

1个回答

91

在Bootstrap 2.x中,Glyphicons使用了图像方法——就像你在问题中提到的那样,使用图片来实现。

使用图像方法的缺点是:

  • 无法更改图标的颜色
  • 无法更改图标的背景颜色
  • 无法增加图标的大小

因此,在Bootstrap 2.x中,很多人使用Font-awesome,因为它使用SVG图标,没有这些限制。

在Bootstrap 3.x中,Glyphicons使用字体方法。

使用字体来表示图标具有比使用图像更多的优势:

  • 可扩展 - 不受客户端设备分辨率的影响
  • 可以使用CSS更改颜色
  • 可以像传统图标一样做任何事情(例如更改不透明度、旋转等)
  • 可以添加描边、渐变、阴影等效果
  • 可以转换为文本(使用连字号)
  • 连字号可以被屏幕阅读器识别
  • 将图标更改为字体只需在CSS中更改字体系列即可

您可以在这里看到使用字体方法创建图标的示例。

因此,在Bootstrap分发中,您可以看到glyphicon字体文件:

fonts\glyphicons-halflings-regular.eot
fonts\glyphicons-halflings-regular.svg
fonts\glyphicons-halflings-regular.ttf
fonts\glyphicons-halflings-regular.woff

Bootstrap CSS使用以下方式引用图标字体:

@font-face {
  font-family: 'Glyphicons Halflings';
  src: url('../fonts/glyphicons-halflings-regular.eot');
  src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}

并且CSS使用 .glyphicon 基础类来链接该字体(请注意font-family):

.glyphicon {
  position: relative;
  top: 1px;
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: normal;
  ...
}

然后每个 glyphicon 都使用一个独立的图标类,该类指向 Glyphicon Halflings 字体中的 Unicode 引用,例如:

.glyphicon-envelope:before {
  content: "\2709";
}
这就是为什么在Bootstrap 3中,您必须将基本的.glyphicon类与各个图标类一起应用于span元素中的原因:
<span class="glyphicon glyphicon-envelope"></span>

2
谢谢@mccannf提供如此详细的解释。顺便说一下,css-tricks.com很棒!谢谢。 - adamsmith
我认为Unicode参考链接中的Unicode字体链接是错误的,因为Unicode字体是完全不同的东西。你可能想要像这个或者这个这样的东西。 - Just a student

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接