Работа с иконками

Алан-э-Дейл       11.03.2024 г.

Оглавление

What is Font Awesome Icons? | Fa Fa Icons

Fa Fa Icons are used for web development. IOS/Android application uses appropriate Fa Fa Icons. Fontawesome Icon is a very easily implementable web application Library. Font awesome icons code has the power of magical ligatures, that turn that text into an icon. These Fa Fa Icons are very customizable which can be modified as per our needs. There are more than 2000 unique Fa Fa Icons listed above. These Icons will make a great User Interface (UI) while users interact with web applications or the website. Font icons list components help users to know easily about the actionable ideas. Strategically using color, typography, and Fa Icons are some best practises for designing an interactive Interface. Font Awesome (Fa — Fa) icons makes users comfortable getting things done more quickly. Page layout also improves a lot after adding proper UI elements.

Let us first understand what is Icon- Icons are basically used as symbols in Website/Application. Just think while travelling on road we see Symbols which provides us important information like — there is U turn, Left turn or Right turn. So all these symbols helps us while travelling. On the same way it is very important to get key information through symbols. The basic exam of icon is search icon on google search button which gives hint to user the purpose of button. In real life no body wants to read long text or waste timing in searching the navigation links or other important information so icons plays key role here. Few years ago people used images to show icons but now things has been changed. Lets see one more example to understand the use of images as icons suppose we have to add 20-30 icons on our website, in this case we need 30 images to show icons. So creating 20-30 images will consume the resource and time as well. To oversome this problem the concept of Fontawesomeicons came into existence. Basically fontawesomeicons is library which contains all possible icons list.

Analysing the Font Awesome CSS classes

After I wasn’t really satisfied with any of the proposed solutions I tried to find a better one.

Let’s break it down

Each icon consists of two CSS classes — the shared «fa» class and an icon-specific class like «fa-car». Setting only the icon-specific class will result in a not very meaningful unicode character:

Result:

The icon isn’t what we want, but at least the tag’s original font remains as is. Using the Google Chrome developer tools I can quickly confirm that the icon-specific class is not doing any harm to the original tag:

Evidently this class only adds the content to the ::before attribute of the target element. The conclusion is that the actual styling gets applied via the «fa» class:

Now this makes sense. The content from the ::before attribute gets rendered inside the original tag and therefore also picks up the styling from the fa class.

Everything from the fa class could equally go into the icon class as part of the ::before attribute, but I can see why the Font Awesome team has extracted it into a shared class, because it is the same for every icon and would be otherwise a maintenance nightmare.

Styling Font Awesome Icons

Now that you have them installed, it’s time to make the icons pop. You can do this using CSS because each of the icons is governed by a CSS class. The two most-often used styles are and size. You can either include the CSS styling in your stylesheets, or you can do it inline. In general, you may want to use inline styling because icons like these don’t tend to be universal across a whole site.

The Font Awesome website has examples of how to do this. They show sizing using their igloo icon and the additional class like fa-xs or fa-xl or fa-2x for specific size.

Additionally, if you need the icon to be relative to a specific size and the absolute values won’t work, you can place it in its own <div> to make it work within your constraints.

<div style="font-size: 0.5rem;">
  <i class="fas fa-igloo fa-10x"></i>
</div>

Font Awesome

Font Awesome — это библиотека, содержащая 439 иконок. Она является абсолютно бесплатной как для личного, так и для коммерческого использования. Изначально она разрабатывалась для Bootstrap, однако вы можете использовать её и отдельно.

Работа с Font Awesome

Самый простой способ подключить Font Awesome — подключить через CDN. Если же вы работаете оффлайн — вам придётся скачать набор иконок.

Так же вам необходимо подключить CSS и сгенерированные шрифты в различных форматах.

Для использования иконок, вы должны разместить их внутри элемента или . Затем, нужно присвоить им два класса: fa плюс второй класс, который должен соответствовать названию иконки, например fa-home. Тут можно найти названия всех доступных иконок.

Дополнительную информацию и множество примеров можно найти на этой странице.

Теперь давайте рассмотрим несколько примеров.

Font Awesome. Пример #1

В первом примере, мы создаём вертикальное меню. Сначала помещаем иконки внутри элемента i и вдвое увеличиваем их размер, используя предопределённый класс fa-2x. Затем оформляем их с помощью CSS.

HTML будет выглядеть следующим образом:

<li>
    <a href="#" data-name="Home">
        <i class="fa fa-home fa-2x"></i>
    </a>
</li>
<li>
    <a href="#" data-name="About">
        <i class="fa fa-bullhorn fa-2x"></i>
    </a>
</li>

А вот и CSS:

nav li {
    background: #ededed;
    height: 80px;
    width: 80px;
    line-height: 80px;
    text-align: center;
}

nav li:not(:first-child) {
      margin-top: 1px;
}

nav li a {
    outline: none;
    position: relative;
    width: 100%;
    height: 100%;
}

nav i {
    color: steelblue;
    vertical-align: middle;
}

nav li a:after {
    background: #ededed;
    content: attr(data-name);
    display: none;
    margin-left: 1px;
    width: 160px;
    height: 80px;
    left: 80px;
    position: absolute;
    font-size: 1.2em;
}

nav li a:hover:after {
    display: inline-block;
}

Font Awesome. Пример #2

В следующем примере мы создадим простой социальный виджет. Снова помещаем иконки внутри элемента i, удваиваем их размер. Затем оформляем с помощью CSS.

HTML для одной иконки будет выглядеть следующим образом:

<a href="#" title="Like us!">
    <i class="fa fa-facebook fa-2x"></i>
</a>

CSS для стилизации значков:

section a {
  padding: 7px;
  color: black;
}

section i {
  vertical-align: middle;
  transition: color .3s ease-in-out;
}

section a:nth-child(1):hover i {
  color: #3b5998;
}

Font Awesome. Пример #3

В третьем примере мы используем значки для формы авторизации. Применяем другой предопределённый fa-fx класс, чтобы установить фиксированную ширину (примерно 1.25em).

HTML и CSS похожи на предыдущие. Результат.

Обратите внимание на иконки в форме, а также на социальные ссылки

Font Awesome Stacked Icons

To stack multiple icons, we need to use  class on the parent, the  for the regularly sized icon, and  for the larger icon and  can be used as an alternative icon color. You can even throw larger icon classes on the parent to get further control of sizing.

Following example shows how to use these classes for icons.

Live Preview

<!DOCTYPE html>

<html>

<head>

<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css»>

<title></title>

</head>

<body>

<span class=»fa-stack fa-lg»>

<i class=»fa fa-square-o fa-stack-2x»></i>

<i class=»fa fa-twitter fa-stack-1x»></i>

</span>

fa-twitter on fa-square-o<br>

<span class=»fa-stack fa-lg»>

<i class=»fa fa-circle fa-stack-2x»></i>

<i class=»fa fa-flag fa-stack-1x fa-inverse»></i>

</span>

fa-flag (inverse) on fa-circle<br>

<span class=»fa-stack fa-lg»>

<i class=»fa fa-camera-retro fa-stack-1x»></i>

<i class=»fa fa-ban fa-stack-2x text-danger» style=»colorred;»></i>

</span>

fa-ban on fa-camera

</body>

</html>

In above example we used classes to make font awesome icons as stacked.

New in Font Awesome 5

New in Font Awesome 5 is the prefix,
Font Awesome 4 uses .

The in
stands for solid, and some icons also have a regular mode,
specified by using the prefix :

Example

<i class=»fas fa-clock»></i>
<i class=»far fa-clock»></i>

Results in:

Font Awesome is designed to be used with inline elements. The and
elements are widely used for icons.

Also note that if you change the font-size or color of the icon’s container, the icon
changes. Same things goes for shadow, and anything else that gets
inherited using CSS.

Example

<i class=»fas fa-clock» style=»font-size:120px;color:#2196F3″></i>
<i class=»far fa-clock» style=»font-size:120px;color:#2196F3″></i>

Results in:

Sizing Icons

The
,
,
,
,
,
,
,
,
,
,
,
or classes are used to adjust the icon sizes relative to their container.

Example

The following code:

<i class=»fas fa-clock fa-xs»></i>
<i class=»fas fa-clock fa-sm»></i><i class=»fas fa-clock fa-lg»></i>
<i class=»fas fa-clock fa-2x»></i>
<i class=»fas fa-clock fa-5x»></i>
<i class=»fas fa-clock fa-10x»></i>

Results in:

List Icons

The and classes are used to replace default bullets in unordered lists.

Example

The following code:

<ul class=»fa-ul»>  <li><span class=»fa-li»><i class=»fas fa-check-square»></i></span>List
Item</li>  <li><span class=»fa-li»><i class=»fas fa-spinner fa-pulse»></i></span>List
Item</li>  <li><span class=»fa-li»><i class=»fas fa-square»></i></span>List
Item</li></ul>

Results in:

Animated Icons

The class gets any icon to rotate, and the
class gets any icon to rotate with 8 steps.

Example

The following code:

<i class=»fas fa-spinner fa-spin»></i><i class=»fas fa-circle-notch fa-spin»></i>
<i class=»fas fa-sync-alt fa-spin»></i><i class=»fas fa-cog fa-spin»></i><i class=»fas fa-cog fa-pulse»></i><i
class=»fas fa-spinner fa-pulse»></i>

Results in:

Note: IE8 and IE9 do not support CSS3 animations.

Rotated and Flipped Icons

The and classes are used to rotate and flip icons.

Example

The following code:

<i class=»fas fa-horse»></i><i class=»fas fa-horse fa-rotate-90″></i><i class=»fas fa-horse fa-rotate-180″></i><i class=»fas fa-horse fa-rotate-270″></i><i class=»fas fa-horse fa-flip-horizontal»></i><i class=»fas fa-horse fa-flip-vertical»></i>

Results in:

Stacked Icons

To stack multiple icons, use the class on the parent, the
class for the regularly sized icon, and for the larger icon.

The class can be used as an alternative icon color.
You can also add larger
icon classes to the parent to further control the sizing.

Example

The following code:

<span class=»fa-stack fa-lg»>  <i class=»fas fa-circle
fa-stack-2x»></i>  <i class=»fab fa-twitter fa-stack-1x fa-inverse»></i>
</span>fa-twitter (inverse) on fa-circle (solid)<br><span class=»fa-stack
fa-lg»>  <i class=»far fa-circle fa-stack-2x»></i>  <i
class=»fab fa-twitter fa-stack-1x»></i></span>fa-twitter on fa-circle
(regular)<br><span class=»fa-stack fa-lg»>  <i class=»fas fa-camera
fa-stack-1x»></i>  <i class=»fas fa-ban fa-stack-2x text-danger»
style=»color:red;»></i></span>fa-ban on fa-camera

Results in:

Fixed Width Icons

Just like letters and other characters, icons can have different widths, and
if you need to vertically align icons like in a list or a menu, this can be a
problem.

The class is used to set icons at a
fixed width.

Example

<p>Fixed Width:</p><div><i class=»fas fa-arrows-alt-v fa-fw»></i> Icon
1</div><div><i class=»fas fa-band-aid fa-fw»></i> Icon
2</div><div><i
class=»fab fa-bluetooth-b fa-fw»></i> Icon 3</div><p>Without Fixed
Width:</p><div><i class=»fas fa-arrows-alt-v»></i> Icon 1</div><div><i
class=»fas fa-band-aid»></i> Icon 2</div><div><i class=»fab fa-bluetooth-b»></i> Icon
3</div>

Results in:

Example

The following code:

<i class=»fas fa-quote-left fa-3x fa-pull-left fa-border»></i>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.

Results in:

❮ Previous
Next ❯

Публикация готового сета иконок Iconmoon на сайте

Скачав архив вы можете подключить его на своем сайте вместо Font Awesome и использовать иконки уже из этого набора, включая вашу собственную иконку. Для подключения на сайте нам понадобятся файлы из папки fonts и style.css — заливаем их к себе на сайт (при необходимости style.css можно переименовать или вообще добавить контент из него в свой css файл, который был использован на сайте ранее)

Обратите внимание, что разместив font и css у себя на сайте относительный путь к шрифтам в css файле мог изменится. По этому откройте уже загруженный на ваш сайт css код и убедитесь, что к шрифтам прописаны верные пути

Вот тут я красным выделил место, где нужно проверить пути.

После успешного переноса файлов iconmon на сайты использовать иконки можно таким образом:

5: Использование иконок

Теперь, когда вы установили все то, что вам нужно, и добавили иконки  в библиотеку Font Awesome, мы можем использовать их и определить их размеры. В этом мануале мы будем использовать пакет light (fal).

В первом примере мы установим нормальный размер:

<FontAwesomeIcon icon={} />

Во втором примере мы попробуем использовать именованный размер, в нем используются сокращения для small (sm), medium (md), large (lg) и extra-large (xl):

<FontAwesomeIcon icon={} size="sm" />
<FontAwesomeIcon icon={} size="md" />
<FontAwesomeIcon icon={} size="lg" />
<FontAwesomeIcon icon={} size="xl" />

Третий вариант – использовать нумерованные размеры (максимальное значение здесь – 6):

<FontAwesomeIcon icon={} size="2x" />
<FontAwesomeIcon icon={} size="3x" />
<FontAwesomeIcon icon={} size="4x" />
<FontAwesomeIcon icon={} size="5x" />
<FontAwesomeIcon icon={} size="6x" />

Нумерованные размеры позволяют использовать десятичные дроби, чтобы подобрать идеальный размер:

<FontAwesomeIcon icon={} size="2.5x" />

Font Awesome стилизует свои SVG, используя цвет текста CSS. Если мы поместим тег <p> туда, где будет расположена иконка, цвет иконки будет совпадать с цветом текста:

<FontAwesomeIcon icon={faHome} style={{ color: 'red' }} />

Font Awesome также предлагает функцию , с помощью которой вы можете объединять различные преобразования в рамках одной строки:

 <FontAwesomeIcon icon={} transform="down-4 grow-2.5" />

Вы можете использовать любые преобразования, перечисленные на сайте Font Awesome: перемещать иконки вверх, вниз, влево или вправо, чтобы добиться идеального позиционирования относительно текста или границ кнопок.

Иконки фиксированной ширины

Если все ваши иконки должны быть одинаковой ширины, Font Awesome позволяет использовать свойство fixedWidth. Допустим, вам нужна фиксированная ширина иконок для выпадающего меню в навигации:

<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />
<FontAwesomeIcon icon={} fixedWidth />

Вращающиеся иконки

Вращение иконок применяется на кнопках форм (в частности при обработке форм). Вы можете использовать вращающуюся иконку, чтобы создать общепринятый эффект для загрузки:

<FontAwesomeIcon icon={} spin />

Вы можете использовать свойство spin где угодно:

<FontAwesomeIcon icon={} spin />

Маскировка иконок (продвинутая функция)

Font Awesome позволяет комбинировать две иконки и создавать таким образом эффекты маскировки. При этом нужно сначала определить обычную иконку, а затем использовать свойство mask, чтобы определить вторую, которая будет расположена поверх первой. Первая иконка при этом будет ограничена размерами маскирующей иконки.

В этом примере мы создали фильтры тегов, используя маскировку:

<FontAwesomeIcon
  icon={}
  mask={}
  transform="grow-7 left-1.5 up-2.2"
  fixedWidth
/>

Обратите внимание: мы можем связать несколько свойств transform и с их помощью переместить внутреннюю иконку так, чтобы она соответствовала маскирующей иконке по размерам. Мы даже можем раскрасить и изменить фоновый логотип с помощью Font Awesome

Мы даже можем раскрасить и изменить фоновый логотип с помощью Font Awesome.

Why Font Awesome Icons Showing as Box?

In order to insert a font icon on your site, you have to have the followings:

  • Host fonts on your server
  • Link correct font awesome CSS version
  • No conflict with old and new versions on the same site
  • Check correct font family
  • Use proper CSS class
  • Check font weight
  • Check CSS content code

Let us check out ease point in detail.

1. Host Fonts on Your Server

In order to use font awesome on your website, it is necessary to host the font files also in the same directory. All web font typefaces should be available in “/webfonts” folder and referenced in the CSS located in “/css” folder.

In most cases, the theme or plugin you use will install all necessary CSS and font files on your server. This is the case, especially when you use WordPress for your website.

2. Link Correct CSS Version

Font awesome was available for free till version 4.70. However, there are both free and pro versions available starting from version 5.0. Though version 4.70 was outdated, most free plugins and themes still uses 4.70 due to the uniform CSS class and ease of use. However, version 5.0 has brands and solid styles for free users and you can use all.css to include both styles.

You can either register with font awesome site to get a CDN kit or use the CDN files available from Cloudflare.


Get Font Awesome CDN Kit

3. Conflicting CSS Versions

One of the problem we have faced with a WordPress site is that a plugin was using version 4.70 and the theme was using 5.0. This was causing the conflict due to incompatible CSS class and content codes. Therefore, make sure to use the latest version 5.0 with proper CSS source file on your site.


Font Icons Showing as Box

4. Use Correct Font Family

In order to use font awesome with CSS, you should use proper font family. Below is the kind of CSS code used in version 4.70.

.li:before {content:”\00A3″;
font-family: “FontAwesome”;
font-weight: normal;
}

However, this will show a box instead of an icon with version 5.0. you should use the following CSS with versions 5.0 free version.

.li:before {content:”\00A3″; font-family: “Font Awesome 5 Free“; font-weight: 900; }

Therefore, make sure to use correct “Font Awesome 5 Free” font family in the CSS. In addition, if you are using social icons then the font family should be “Font Awesome 5 Brands”. These are the two font families available for free users.

5. Use Proper CSS Style Prefix

Another confusion is that version 5.0 has different CSS classes than the previous versions. On version 4.7 you can use the fa style prefix like below:

<i class=”fa fa-camera”></i>

However, this will not work with version 5.0 onwards. The fa style prefix was deprecated and you should use fas for solid icons and fab for social branding icons like Facebook.

6. Check Font Weight

Font awesome version 5.0 does not support general “font-weight:normal” declaration in CSS. You should declare specific font weight for the icon to show up.

7. Check CSS Content Code

The last point is to make sure the content code used in CSS is correct. You have to use one of the available code in from the font awesome site in CSS pseudo element. In addition, ensure to use the code in the format “\f00d”; to show the icon correctly.

Font Awesome Fixed width Icons

By using  class we can set fixed width to icons. This will be useful when different icon widths throw off alignment in navigation menus and group lists. Following example shows how to use fixed width class in icons.

Live Preview

<!DOCTYPE html>

<html>

<head>

<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css»>

<title></title>

</head>

<body>

<div class=»list-group»>

<a class=»list-group-item» href=»#»><i class=»fa fa-home fa-fw»></i>&nbsp; Home</a>

<a class=»list-group-item» href=»#»><i class=»fa fa-book fa-fw»></i>&nbsp; Library</a>

<a class=»list-group-item» href=»#»><i class=»fa fa-pencil fa-fw»></i>&nbsp; Applications</a>

<a class=»list-group-item» href=»#»><i class=»fa fa-cog fa-fw»></i>&nbsp; Settings</a>

</div>

</body>

</html>

 In above code we used  class to set fixed width for icons. Now will run and see the output.

Font Awesome 5

Font Awesome 5 IntroIcons AccessibilityIcons AlertIcons AnimalsIcons ArrowsIcons Audio & VideoIcons AutomotiveIcons AutumnIcons BeverageIcons BrandsIcons BuildingsIcons BusinessIcons CampingIcons CharityIcons ChatIcons ChessIcons ChildhoodIcons ClothingIcons CodeIcons CommunicationIcons ComputersIcons ConstructionIcons CurrencyIcons Date & TimeIcons DesignIcons EditorsIcons EducationIcons EmojiIcons EnergyIcons FilesIcons FinanceIcons FitnessIcons FoodIcons Fruits & VegetablesIcons GamesIcons GendersIcons HalloweenIcons HandsIcons HealthIcons HolidayIcons HotelIcons HouseholdIcons ImagesIcons InterfacesIcons LogisticsIcons MapsIcons MaritimeIcons MarketingIcons MathematicsIcons MedicalIcons MovingIcons MusicIcons ObjectsIcons Payment & ShoppingIcons PharmacyIcons PoliticalIcons ReligionIcons ScienceIcons Science FictionIcons SecurityIcons ShapesIcons ShoppingIcons SocialIcons SpinnersIcons SportsIcons SpringIcons StatusIcons SummerIcons Tabletop GamingIcons ToggleIcons TravelIcons Users & PeopleIcons VehiclesIcons WeatherIcons WinterIcons Writing

Интеграция с Font Awesome

Конечно, вы можете рассматривать новый шрифт как отдельный набор иконок. Но разве не было бы круто расширить сам набор Font Awesome? Давайте сделаем это!

Единственная вещь, которую нужно понять, заключается в том, что мы будем наследовать CSS стили, определённые Font Awesome CSS файлом. Например, он будет содержать примерно такую запись:

Это значит, что когда мы следующим образом определяем элемент иконки, она будет наследовать стили , и из кода выше:

Теперь давайте определим наш собственный CSS файл. Назовём файл .

Первой записью в этом файле должно идти объявление правила font-face. Может быть сделано как ниже. Это несложно. Лишь немного базового CSS.

Далее мы можем определить желаемые иконки:

Обратите внимание, что мы определяем иконки как псевдо-элементы, используя селектор. Таким образом, мы можем внедрить нужный нам контент внутрь элемента, который использует объявленные классы

В созданном нами шрифте FontMoreAwesome “A”, “B” и “C” обозначаются иконками для Troll, Lol и Like-a-boss соответственно. Хотя это не лучший способ сделать это.

Font Awesome использует области для частного использования (Unicode Private Use Area, PUA), чтобы застраховать экранные читалки от зачитывания случайных символов, которые и представляют собой иконки.

Но, для простоты рассказа, в нашем примере мы будем держаться букв английского алфавита.

Ещё один момент, достойный упоминания — в примере выше, при внедрении на страницу своего контента, мы перезаписываем правило font-family, определённое Font Awesome.

Installing Font Awesome

While there is a manual way to install and use Font Awesome, there’s a better way for WordPress users. The fine folks over at FA have released an official Font Awesome WordPress plugin, and it works beautifully.

With the plugin installed and activated, you now have access to the `icon name` shortcode as well as the HTML snippets. As long as you keep the handy-dandy FA icon list around so you know exactly what icon you need. You will see on the plugin’s settings page (found under Settings – Font Awesome) how things are set up by default. In general, these are fine to keep and use. Most people won’t need anything else.

The Method option is probably the most important for most folks. You can toggle between Webfont or SVG. While SVG gives you more power and features (such as power transforms and masking), the Font Awesome CDN will deliver the icons as SVG files and not as a font. While that is better in some ways, the SVG isn’t recognized by as many browsers, nor does WordPress always play well with SVG images. So we suggest playing it safe with the webfont version.

So does Font Awesome, for that matter: If you’re not sure of the difference, or don’t know why you’d need to use SVG, then sticking with the default webfont method is probably easiest.

To use the Font Awesome icons on your WordPress site,  it’s simple. Just add <i class=”fab fa-wordpress”></i> anywhere you want an icon to appear. Make sure to check the icon library to know what name to put in.

Note: the shortcodes in the plugin are hit-and-miss. Some icons render perfectly well, while others show up blank. We recommend you stick to the HTML insertion unless you see that the shortcode works for you. See below for an example of the WordPress example above not rendering, while the camera icon does.

And you’re done. The Font Awesome WordPress plugin is great for folks who aren’t comfortable going into their theme or files to insert the otherwise required code. However, if you are comfortable doing that, you can follow these instructions to get the Font Awesome icons on your site.

2: Выбор иконок

Прежде чем мы продолжим работу, важно разобраться, как структурированы библиотеки Font Awesome. Поскольку иконок в библиотеке очень много, команда решила разделить их на несколько пакетов

Чтобы изучить возможные варианты и выбрать необходимые иконки, рекомендуется посетить специальную страницу на сайте Font Awesome. В левой части этой страницы вы найдете различные фильтры – они очень важны, потому что именно они сообщают, из какого пакета импортировать ту или иную иконку.

В приведенном выше примере мы извлекли иконку из пакета @fortawesome/free-solid-svg-icons.

Как определить, какому пакету принадлежит иконка?

Чтобы определить, к какому пакету относится нужная вам иконка, просмотрите на фильтры слева. Также можно кликнуть на иконку и увидеть пакет, которому он принадлежит.

Когда вы узнаете название необходимого вам пакета, важно запомнить его трехбуквенное сокращение:

  • Solid Style – fas
  • Regular Style – far
  • Light Style – fal
  • Duotone Style – fad

Найти определенный тип можно в левой панели на странице иконок.

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

Если вы внимательно просмотрите страницу иконок на сайте Font Awesome, вы заметите, что одна и та же иконка обычно существует в нескольких версиях. Например, введите в поиск boxing-glove – в результате вы увидите три иконки.

Чтобы использовать конкретную иконку, вам необходимо настроить <FontAwesomeIcon>. Ниже мы приведем несколько типов одной и той же иконки из разных пакетов. К ним относятся трехбуквенные сокращения, о которых мы говорили ранее.

Примечание: Следующие примеры не будут работать, пока мы не создадим библиотеку иконок – мы сделаем это немного позже.

Вот пример для пакета solid:

<FontAwesomeIcon icon={} />

Этот пакет используется по умолчанию, если не указано другое:

<FontAwesomeIcon icon={faCode} />

Пакет light используется с помощью сокращения fal:

<FontAwesomeIcon icon={} />;

Свойство icon нужно было изменить со строки на массив.

What is Font Awesome exactly?

Font Awesome is a font that’s made up of symbols, icons, or pictograms (whatever you prefer to call them) that you can use in a webpage, just like a font.

Don’t know how to set up Font Awesome? Go check out the offical getting started guide, or simply just include this line in your tag:

(Font Awesome hosting very kindly provided by )

Counterpoint

Icon fonts aren’t the only way to implement icons on the web. If you’re looking for a explanation of using icon fonts vs. SVG files (another possible method), I’d suggest reading this excellent post by Ian Feather: Ten reasons we switched from an icon font to SVG.

Как обновлять ваш сет с иконками в будущем

Итак, мы успешно создали, подключили и используем свой кастомизированый шрифт Iconmon, в которому у нас и свои иконки и Font Awesome и любые другие. Мы хорошо поработали при генерации этого шрифта, долго прописывали названия к иконкам, выставляли цвета, вертели их редактировали. А теперь у нас появилась еще одна новая иконка и мы хотим ее добавить в этот наш шрифт. Iconmon предлагает 3 варианта решения этой задачи:

  1. Хранение ваших проектов в облаке Iconmon — это платная услуга. При регистрации в Iconmon можно выбрать подписку, оплатить ее и ваши проекты шрифтов будут храниться в вашем аккаунте. Вы всегда сможете изменить их, поставить версию выше, скачать и использовать.
  2. Если вы не чистили кэш браузера, то ваши проекты также останутся при повторном заходе на IconMon и вы сможете легко добавить новую дополнительную иконку в ваш проект и сохранить себе обновленный шрифт. Главная проблема в том, что после того, как вы почистите кеш в браузере, все это будет удалено.
  3. Настройки проекта в файле selection.json — наиболее подходящий вариант для нас. Во-первых — это бесплатно. Этот файл вы скачиваете в архиве со шрифтом каждый раз, когда генерируете его.
    Просто храните этот файл и в будущем можно будет заходить на IconMo и импортировать ваши проекты через него.

Создание шрифта

Первый этап в нашем приключении заключается в создании шрифта Font More Awesome, что можно сделать используя инструкцию на их веб-сайте. Сперва нужна скачать шаблон. Вот пример:

Теперь мы должны заполнить секции желаемыми изображениями. Вы можете распечатать шаблон и нарисовать в нём иконки от руки, или использовать инструмент вроде Adobe Photoshop, GIMP с изображениями, которые вы скачаете из интернета.

После заполнения шаблона, он будет выглядить примерно так:

Следующая вещь, которую вы должны сделать, достаточно проста. Загрузите заполненный шаблон на calligraphr, и нажмите на кнопку “build font” — и БУМ! Вы можете скачать ваш персональный шрифт. Давайте назовём его .

Если вам интересно, что за магия только что произошла — это называется векторизация графики. Из-за воздействия специальных алгоритмов, производящих векторизацию, вы можете заметить некоторые отличия между использованным изображением и созданной иконкой. Зато, после конвертации в векторный формат, изображение может масштабироваться без потерь качества.

Examples

Note: For simplicity & clarity, in these examples Font Awesome has been paired up with the web components from Bootstrap 3. However, Font Awesome can be used in any website or web framework.

You can use glyphicons in a variety of ways; in buttons, button groups for a toolbar, navigation or prepended form inputs. Here are a few examples of glyphicons in action.

Star

<button type="button" class="btn btn-default btn-lg">
          <i class="fa fa-star"></i> Star </button>
        
          <div class="btn-toolbar" role="toolbar"> 
              <div class="btn-group"> 
                  <button type="button" class="btn btn-default"> 
                    <i class="fa fa-align-left"></i> 
                  </button>
                 <button type="button" class="btn btn-default"> 
                    <i class="fa fa-align-center"></i>  
                  </button>
                   <button type="button" class="btn btn-default"> 
                     <i class="fa fa-align-right"></i> 
                  </button>
                  <button type="button" class="btn btn-default"> 
                     <i class="fa fa-align-justify"></i> 
                   </button>
               </div> 
          </div> 

Form Inputs

                <div class="input-group input-group-lg">
                <span class="input-group-addon">
                  <i class="fa fa-envelope"></i>
                </span>
                <input class="form-control" type="text" placeholder="Email address">
            </div>
            <div class="input-group input-group-lg">
                <span class="input-group-addon">
                  <i class="fa fa-lock"></i>
                </span>
                <input class="form-control" type="password" placeholder="Password">
            </div> 

Font Awesome 5

Font Awesome 5 has a PRO edition with 7842 icons, and a FREE edition with 1588 icons. This tutorial will concentrate on the FREE edition.

To use the Free Font Awesome 5 icons, you can choose to download the Font
Awesome library, or you can sign up for an account at Font Awesome, and get a
code (called KIT CODE) to use when you add Font Awesome to your web page.

We prefer the KIT CODE approach. Once you get the code you can start using
Font Awesome on your web pages by including only one line of HTML code:

<script src=»https://kit.fontawesome.com/yourcode.js» crossorigin=»anonymous»></script>

Example

We got the code and by inserting
the script tag, with the code, we can start using Font Awesome:

<!DOCTYPE html><html><head>
<script src=»https://kit.fontawesome.com/a076d05399.js» crossorigin=»anonymous»></script></head><body><i class=»fas fa-clock»></i></body></html>

Results in:

Note: No downloading or installation is required!

Change Font Awesome Icons Size

By using  (33% increase), ,,, or  classes we can increase size of icons relative to container. Following example shows how to use these classes to increase size of icons.

Live Preview

<!DOCTYPE html>

<html>

<head>

<link rel=»stylesheet» href=»https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css»>

<title></title>

</head>

<body>

<i class=»fa fa-desktop fa-lg»></i>

<i class=»fa fa-desktop fa-2x»></i>

<i class=»fa fa-desktop fa-3x»></i>

<i class=»fa fa-desktop fa-4x»></i>

<i class=»fa fa-desktop fa-5x»></i>

</body>

</html>

In above example we are changing size of icons using ,,, or  classes.

Добавление иконок через Icomoon

IconMon — онлайн сервис для создания собственных шрифтов из иконок для использования на сайтах или в мобильных и дектопных приложениях. Допустим у вас подключен Font Awesome, а вам нужно добавить иконки из других шрифтов или вообще свою собственную иконку с вашим логотипом. Для этого вы создаете новый проект в IconMon, импортируете в него Font Awesome шрифт, если нужно то другие шрифты или свои иконки в виде шрифтов/svg картинок. Затем вы скачиваете получившийся шрифт и используете в своем приложении вместо Font Awesome. Ниже я покажу как это делать пошагово.

IconMon: начало работы

Заходим на сайт сервиса iconmon.io и жмем кнопку IcoMoon App
При запуске IconMon вы попадете на экран управления проектом. В нем по дефолту уже будет список бесплатных иконок, которые нам предлагает IconMon. Так как наша задача была в том,
чтобы обновить шрифт Font Awesome, то первое что мы сделаем — это импортируем его в IcoMoon.
Жмем кнопку Import Icons (в верхнем левом углу) и выбираем файл fontawesome-webfont.svg из папки шрифтов, которую вы использовали ранее.
Отлично. После того, как мы добавили Font Awesome, загрузим и свою собственную иконку в svg формате тем же способом (Import Icons).
Теперь все необходимые иконки и наборы иконок загружены в систему мы можем по необходимости их немного исправить или просто изменить. Для этого в верхнем меню управления переключите режим с «Select» на «Edit» и выберите иконку в таблице иконок. При редактировании можно выполнять следующие операции: Разворот/Отражение иконки (Rotate), Масштабирование (Scale), Выравнивание (Align), Цвет (Color).
После редактирования (если оно было необходимо) и загрузки нужных иконок в IconMon нам нужно отметить те, которые будут в нашем новом шрифте. Для этого в верхнем меню выбираем (если не выбрано) Select и отмечаем нужные иконки. Также Вы можете выбрать сразу весь набор. У нас есть загруженный набор Font Awesome — справа от заголовка набора нажимаем на кнопку управления и выбираем Select All. Не забываем отметить нашу собственную иконку.
В нижнем правом углу экрана нажимаем Generate Font. После нажатия мы попадем на экран просмотра шрифта, который мы создали. На этом экране можно указать или исправить названия иконок

Также обратите внимание, на дополнительные опции рядом с кнопкой Download. В этих опциях можно указать название, различную мета-информацию и указать способ, которым иконки будут вставляться у вас на сайте

Также можно указать версию шрифта.
Убедившись, что все нужные правки созданы, нажимаем на кнопку Download и скачиваем новый шрифт.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.