Alerts

Содержание:

Как использовать стандартные иконки в Bootstrap 3?

Добавление иконки Bootstrap на веб-страницу обычно осуществляется с помощью элемента или , к которому необходимо добавить базовый класс и класс определённой иконки (например, иконки телефона — ).

<!-- Глификонка телефона -->
<!-- 1. С помощью элемента span -->
<span class="glyphicon glyphicon-earphone" aria-hidden="true"></span>
<!-- 2. С помощью элемента i -->
<i class="glyphicon glyphicon-earphone" aria-hidden="true"></i>

Стилизация иконок в Bootstrap 3

Оформление иконок Glyphicons Halflings осуществляется также как и стилизация обычного текста.

Например, для того чтобы изменить цвет иконки, ей необходимо просто задать CSS-свойство .

<!-- Иконка "Стрелочка влево" (glyphicon-arrow-left) -->
<!-- Например, с помощью атрибута style -->
<i class="glyphicon glyphicon-arrow-left" aria-hidden="true" style="color: green;"></i>
<!-- Например, с помощью класса (например, glyphicon-green) -->
<style>
/* CSS */
.glyphicon-green {
  color: green;
}
</style>
<i class="glyphicon glyphicon-arrow-left glyphicon-green" aria-hidden="true"></i>

Изменение размера иконки Glyphicon осуществляется с помощью CSS свойства :

<!-- Например, увеличим размер иконки -->
<i class="glyphicon glyphicon-eye-open" style="font-size: 40px;"></i>

Добавление иконок Bootstrap к HTML-элементам

Помещение иконки «Звездочка» в кнопку выполняется следующим образом:

<!-- Разделение иконки и текста с помощью пробела -->
<button type="button" class="btn btn-danger btn-lg">
  <span class="glyphicon glyphicon-star"></span> Избранное
</button>
<!-- Разделение иконки и текста с помощью   -->
<button type="button" class="btn btn-default btn-lg">
  <span class="glyphicon glyphicon-star"></span> Избранное
</button>

Скриншот примера:

Не забудьте оставить место между значком и текстом, чтобы обеспечить необходимое расстояние. Например, посредством пробела или специсимвола .

Использование иконки Bootstrap в качестве маркера списка ul.

Чтобы это осуществить необходимо:

  1. добавить класс к элементу ;
  2. вставить на страницу фрагмент CSS кода.
<style>
/* CSS */
ul.icon {
  /* список без стандартного маркера */
  list-style-type: none;
}
ul.icon li {
  /* отступ слева */
  text-indent: 0px;
}
ul.icon li:before {
  /* шрифт */
  font-family: 'Glyphicons Halflings';
  /* код иконки */
  content: "\e127";
  /* расположение блока с иконкой */
  float: left;
  /* ширина блока */
  width: 35px;
}
</style>
  
<!-- Маркированный список ul -->
<ul class="icon">
  <li>Содержимое 1 пункта</li>
  <li>Содержимое 2 пункта</li>
  <li>Содержимое 3 пункта</li>
</ul>

Пример, как иконку можно поместить в элемент input:

<style>
/* CSS */
.input-icon {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  display: block;
  width: 34px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  pointer-events: none;
  top: 25px;
}
.form-icon {
  position: relative;
}
.form-icon input {
  padding-left: 42.5px;
}
</style>
  
<!-- HTML -->
<div class="form-group form-icon">
  <label class="control-label" for="name-user">Имя пользователя:</label>
  <input class="form-control" id="name-user">
  <i class="glyphicon glyphicon-user input-icon" aria-hidden="true"></i>
</div>

A bit of history

Before we get to know what’s new in the version 2.0, I searched my mind (and changelog files 😉 and tried to briefly summarize and comment the sequence of all major events that shaped GLYPHICONS into its present form.

  • 1.0 released 11/11/2010

    GLYPHICONS icons were born with 170 icons in one set, for 49 USD. If you’re curious, you may read more about why they exist in newly updated page: “Motivation behind icons”.

  • 1.1 released 12/21/2010

    * 50 new icons were created
    * 36 icons changed or redesigned
    * 1 icon removed(220 icons in total)

  • 1.2 released 2/13/2011

    * 50 new icons were created
    * 21 icons changed or redesigned(270 icons in total)

  • 1.3 released 5/11/2011

    * 50 new icons were created
    * 15 icons changed or redesigned
    * 10 icons removed(310 icons in total, still only in one set)

  • 1.4 released 8/7/2011

    * new Halflings set was created — 100 tiny 12px icons
    * 22 new icons in the Basic set were created
    * 22 icons changed or redesigned in the Basic set
    * 2 icons removed(330 icons in Basic set and 100 in Halflings set)

  • 1.5 released 12/20/2011

    * 20 new icons in Halflings set
    * 50 new icons in Basic set
    * 39 icons changed or redesigned
    * 30 icons removed(350 icons in Basic set and 120 in Halflings set)

  • 1.6 released 4/11/2012

    * 20 new icons in Halflings set
    * 50 new icons in Basic set
    * 14 icons changed or redesigned(400 icons in Basic set and 140 in Halflings set)

  • 1.7 released 11/1/2012

    * font and HTML/CSS example files were added for both sets along with
    * vector version of Halflings added
    * 20 new icons in Halflings set
    * 27 new icons in Basic set
    * 7 icons redesigned
    * 7 icons removed
    * the change of the price from 49 to 59 USD(420 icons in Basic set and 160 in Halflings set)

  • 1.8 released 7/24/2013

    * new website, including integrated search among all icons
    * 50 Social set, a new set of icons
    * 130 Filetypes set, a new set of icons
    * simplified and improved HTML/CSS code for all icons
    * all icons also as individual and paged PDF files(470 icons in Basic set, 200 in Halflings set, 130 in Filetypes set and 50 in Social set)

  • 1.9 released 11/24/2014

    * 140 new icons in Basic set
    * 60 new icons in Halflings set
    * 10 new icons in Social set
    * 20 icons changed or redesigned
    * all icons also in @3x size
    * all icons also as individual SVG files(610 icons in Basic set, 260 in Halflings set, 130 in Filetypes set and 60 in Social set)

  • 1.9.2 released 12/15/2015

    * 190 new icons in Basic set
    * 40 new icons in Halflings set
    * 10 new icons in Filetypes set
    * 13 new icons in Social set
    * 58 icons changed or redesigned
    * 7 icons removed(800 icons in Basic set, 300 in Halflings set, 140 in Filetypes set and 70 in Social set)

  • 2.0 released 10/23/2018

    * GLYPHICONS Basic set contains 900 icons, all created from scratch
    * GLYPHICONS Halflings set contains 240 icons, all created from scratch
    * GLYPHICONS Filetypes set contains 80 icons, all created from scratch
    * GLYPHICONS Social set was replaced with a new Social tool
    * Brand new website — including better search and info page for each icon set
    * Brand new Handbook — with a new content, which reflects a new file structure(900 icons in Basic set, 240 in Halflings set, 80 in Filetypes set)

    What was discontinued
    * HTML/CSS files — including Bootstrap files and icon font for the web
    * FREE, ALL and PRO versions — each set is now offered separately ()

This timeline nicely illustrates, how this project gradually grew in time and show the fact, that GLYPHICONS were never about quantity (and they never will be), but rather about quality in the first place. That’s not just a phrase, that’s why icons weren’t only created, but from time to time some were also removed and many of them changed or completely redesigned.

Using logos in an appropriate place

The context is very important and often neglected. Again, many brands have already specified the list of places where their logo can be used or on the opposite, the list of forbidden places. Either way, you should always consider logos surroundings and respect what is already defined in brand guidelines. In particular, you should pay attention to:

  • that you don’t mislead the user by creating the impression that you represent the brand in any way
  • be sure that you‘re primarily using buttons created by brand owner and that you’re not creating your own graphic where it’s not allowed etc.
  • some brands allows to use their logo only on certain medium, for example Facebook specifically requires prior consultation and their consent to the use of their logo on TV or film
  • other brands can control when you may use their logo as a link, for example YouTube logo can be used as a link only when the destination URL is a YouTube channel

There are tons of other various limitations and each brand has its own specific features in this regard. At any rate, you should always double-check, if you don’t violate any brand-specific rules.

Page defaults

The and elements are updated to provide better page-wide defaults. More specifically:

  • The is globally set on every element—including and , to . This ensures that the declared width of element is never exceeded due to padding or border.
  • No base is declared on the , but is assumed (the browser default). is applied on the for easy responsive type-scaling via media queries while respecting user preferences and ensuring a more accessible approach.
  • The also sets a global , , and . This is inherited later by some form elements to prevent font inconsistencies.
  • For safety, the has a declared , defaulting to .

Как подключить иконки Glyphicons Halflings?

В стандартной сборке Bootstrap 3 иконки Glyphicons Halflings подключать не надо. Они и так уже подключены в файле CSS ( или ).

Находятся иконки Glyphicons Halflings в каталоге . В данной директории находятся несколько форматов (, , , , ) одних и тех же иконок.

Формат необходим для отображения иконок в старых браузерах Microsoft Internet Explorer (до 9 версии). Шрифт в формате используется для отображения иконок в устаревших браузерах операционной системы Android (до версии 4.4). и – это форматы, которые используют все основные браузеры. Вторая версия формата шрифта () отличается от первой тем, что она имеет меньший размер. В настоящее время поддерживается браузерами Chrome 36+, Opera 26+, Firefox 35+. Шрифт в формате поддерживается только браузерами Safari (4.1 и ниже), работающими под управлением операционной системы iOS.

По умолчанию шрифты Glyphicons Halflings должны быть расположены относительно файла или следующим образом:

bootstrap.css -> родительский каталог -> папка fonts -> шрифты

Если иконки Bootstrap отображаются у вас на странице квадратиками, то проверьте, правильно ли у вас расположены шрифты, относительно файла по вышеприведённой схеме.

Usage

Bootstrap Icons are SVGs, so you can include them into your HTML in a few ways depending on how your project is setup. Bootstrap Icons include a and of by default to allow for easy resizing via .

Sprite

Use the SVG sprite to insert any icon through the element. Use the icon’s filename as the fragment identifier (e.g., is ). SVG sprites allow you to reference an external file similar to an element, but with the power of for easy theming.

Copy the Bootstrap icons SVGs to your directory of choice and reference them like normal images with the element.

CSS

You can also use the SVG within your CSS (be sure to escape any characters, such as to when specifying hex color values). When no dimensions are specified via and on the , the icon will fill the available space.

The attribute is required if you wish to resize icons with . Note that the attribute is required.

Working with SVGs

SVGs are awesome to work with, but they do have some known quirks to work around. Given the numerous ways in which SVGs can be used, we haven’t included these attributes and workarounds in our code.

  • Focus handling is broken in Internet Explorer and Edge. When embedding your SVGs, add to the element. Learn more on Stack Overflow.

  • Browsers inconsistently announce SVGs as tags with voice assistance. Include when possible to avoid any issues.

  • Safari skips when used non-focusable SVGs. As such, use when embedding the file and use CSS to visually hide an equivalent label.

New price for the sets

Last but not least, with this new version, I had to set some price for each new set. As you may see in the , these icons were never made to make money, as the first version was sold as 170 icons for $49 and today it’s a $89 for 900 icons, which is less than $0.09 per icon (!),, with a lifetime commercial license. And I don’t even mention the fact that the quality of icons in version 2.0 is absolutely incomparable with the initial version. Yes, these icons has come a long way and evolved alongside my skills and knowledge improved.

Don’t get me wrong, this project is definitely helping me to pay my monthly bills, but when you deduct all the expenses and time needed for each version, research, new icons, updates, it’s not exactly a gold mine. I always wanted to keep all these icons as affordable as possible to a wide range of users, that’s why I did almost no price changes during the whole time. As before, I’ll try to reward early adopters of any set with free updates.

Objective

Font Icons are becoming more and more popular because of a number of benefits. In this tutorial, we will discuss how to use and customize Glyphicons with Twitter Bootstrap 3. We will also explain the CSS rules work behind, which will give you a better idea of how icon fonts work in general. So that, you become conversant with working any icon font set besides Glyphicons.

What is Glyphicons

Glyphicons are icon fonts which you can use in your web projects. Though you need commercial licensing for using Glyphicons, but you can use them with Twitter Bootstrap based projects for free. Only thing is, it is recommended that you shall provide a link back to the Glyphicon website.

Obtaining Glyphicons

If you have downloaded Bootstrap 3 from https://github.com/twbs/bootstrap/releases/download/v3.0.2/bootstrap-3.0.2-dist.zip (or any previous 3x version), you may find glyphicons within fonts folder within dist folder. There are four files — glyphicons-halflings-regular.eot, glyphicons-halflings-regular.svg, glyphicons-halflings-regular.ttf and glyphicons-halflings-regular.woff. Associated CSS rules are present within bootstrap.css and bootstrap-min.css files within css folder of dist folder.

How to use

In general, we may derive that common syntax for using Glyphicons with Bootstrap 3 is following

Where * is any of the many keywords each representing a specific icon. The following example shows how to use it with the button.

You may view a live demo of the example here

Glyphicon with navbar

Explanation of CSS rules behind

Following CSS rules constitute glyphicon class

So the font face rule actually declares font-family and locations where glyphicons found.

.glyphicon class declares a relative position 1px from the top, it is rendered as inline-block, declares font family, states font style and weight both are normal, sets line height as 1. Besides, it uses -webkit-font-smoothing: antialiased and -moz-osx-font-smoothing: grayscale; which are used for achieving cross-browser consistency.

Then there is

For empty glyphicon.

After this, there are 200 classes each for one icon. Common Format of those classes is as follows

For example, for user icon used in our example, the class is as follows

Now we have seen how to use it, we will see how to customize the Glyphicons.

We will start with our previous example and make customization by changing font size, color and applying text shadow to make the icon look different.

Following is the code we will start with

And here is how it looks

Customizing font size

By increasing or decreasing the font size of the icons, you can make the icons look bigger or smaller.

Customizing color

Applying text shadow

Hope this will get started with using and customizing Glyphicons with your Twitter Bootstrap based projects.

Questions? Suggestions? Join the discussion below. For the upcoming tutorials, please subscribe to our Feed.

Previous: Twitter Bootstrap Typography tutorialNext:
Twitter Bootstrap Tables tutorial

How it began

After school, I started to work in an advertising agency focused on sign-making. In this period of my life, I acquired the most of practical experience with various materials for advertising and printing production.

But once I started my career as a freelance graphic designer, the scope of my everyday work has expanded from printed design only, to web and mobile app interface design as well, almost overnight. During that time, I found myself desperately in need of the source of high quality symbols and icons.

From my previous job, I knew a great collection of AIGA symbol signs, created by Roger Cook and Don Shanosky. Later, as I started to read more about typography and symbols, I discovered Otto Neurath’s Isotypes (work of graphic artist Gerd Arntz) or famous icons made by Susan Kare for the Apple Macintosh. Those have affected me the most, but of course, there were many others which I may not even realize.

I had very low confidence that I could create anything at least remotely useful as they did, but I had to try at least, otherwise I would have been left without a tool I needed so much.

Web HTML/CSS files

It seemed like a good idea to add example HTML/CSS files to each icon set, so I hired a friend and we created a simple HTML/CSS file for each set, which should help people to get the idea how it’s possible to use them and show them how as an example.

But things began to complicate in a moment, when customers started using these files as a framework, instead of as an example. Again, I can’t blame them; I should somehow prevent this and explain better the purpose of these files. It really turned out to be a bit irresponsible and short-sighted from me.

The first problem appeared as the total number of icons in one font file exceeded a certain amount (especially in Basic set as there were 800 icons) and the file size of web fonts started to be ridiculously large, which obviously got worse with each update. You can add to that other problems such as: web icon font rendering issues in various browsers and in certain operating systems and I don’t even mention accessibility problems, when fonts didn’t load properly or at all.

Overall, even though web icon fonts have some advantages, such as fewer HTTP requests and speed when using a large amount of icons on one site, now it looks like we have a better way how to include icons on websites — also in vectors, but more semantic, accessible and user-friendly; yes, it’s SVG.

I’m not a programmer and my knowledge of HTML/CSS faded away during last years, as my focus shifted almost wholly to the graphic design, so if you’re eager for some arguments, I am going to refer you to the article that made me rethink web icon fonts in my projects: Inline SVG vs Icon Fonts by Chris Coyier.

Example

Badges scale to match the size of the immediate parent element by using relative font sizing and units.

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New
Example heading New

Badges can be used as part of links or buttons to provide a counter.

Notifications 4

Note that depending on how they are used, badges may be confusing for users of screen readers and similar assistive technologies. While the styling of badges provides a visual cue as to their purpose, these users will simply be presented with the content of the badge. Depending on the specific situation, these badges may seem like random additional words or numbers at the end of a sentence, link, or button.

Unless the context is clear (as with the “Notifications” example, where it is understood that the “4” is the number of notifications), consider including additional context with a visually hidden piece of additional text.

Profile 9
unread messages

Contextual variations

Add any of the below mentioned modifier classes to change the appearance of a badge.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Conveying meaning to assistive technologies

Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (e.g. the visible text), or is included through alternative means, such as additional text hidden with the class.

Pill badges

Use the modifier class to make badges more rounded (with a larger and additional horizontal ). Useful if you miss the badges from v3.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Using the contextual classes on an element quickly provide actionable badges with hover and focus states.

Example

Badges scale to match the size of the immediate parent element by using relative font sizing and units.

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New
Example heading New

Badges can be used as part of links or buttons to provide a counter.

Notifications 4

Note that depending on how they are used, badges may be confusing for users of screen readers and similar assistive technologies. While the styling of badges provides a visual cue as to their purpose, these users will simply be presented with the content of the badge. Depending on the specific situation, these badges may seem like random additional words or numbers at the end of a sentence, link, or button.

Unless the context is clear (as with the “Notifications” example, where it is understood that the “4” is the number of notifications), consider including additional context with a visually hidden piece of additional text.

Profile 9
unread messages

Contextual variations

Add any of the below mentioned modifier classes to change the appearance of a badge.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Conveying meaning to assistive technologies

Using color to add meaning only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (e.g. the visible text), or is included through alternative means, such as additional text hidden with the class.

Pill badges

Use the modifier class to make badges more rounded (with a larger and additional horizontal ). Useful if you miss the badges from v3.

Primary
Secondary
Success
Danger
Warning
Info
Light
Dark

Using the contextual classes on an element quickly provide actionable badges with hover and focus states.

Labels

Labels are used to provide additional information about something:

Example New

Example New

Example New

Example New

Example New
Example New

Use the class,  followed by
one of the six contextual classes , , ,
, or , within
a element to create
a label:

Example

<h1>Example <span class=»label label-default»>New</span></h1>
<h2>Example <span class=»label label-default»>New</span></h2>
<h3>Example <span class=»label label-default»>New</span></h3>
<h4>Example <span class=»label label-default»>New</span></h4>
<h5>Example <span class=»label label-default»>New</span></h5>
<h6>Example <span class=»label label-default»>New</span></h6>

The following example shows all contextual label classes:

Default Label
Primary Label
Success Label
Info Label
Warning Label
Danger Label

Example

<span class=»label label-default»>Default Label</span>
<span class=»label label-primary»>Primary Label</span>
<span class=»label label-success»>Success Label</span>
<span class=»label label-info»>Info Label</span>
<span class=»label label-warning»>Warning Label</span>
<span class=»label label-danger»>Danger Label</span>

❮ Previous
Next ❯

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *