How to add favicon to html
How to add favicon to html
Создание favicon для сайта 2020
Что такое favicon и для чего он нужен?
Favicon – это значок (иконка), который отображается во вкладке браузера, закладках, а также в сниппетах результатов поиска.
Favicon играет важную роль в веб-приложениях. Он может улучшить внешний вид сайта в выдаче, повышает узнаваемость вашего сайта, помогает пользователю быстро найти необходимую страницу в закладках и вкладках.
Кроме того, пользователь может добавить страницу вашего сайта на главный экран телефона или сохранить как веб-приложение. В таком случае с помощью favicon можно быстро найти сайт среди большого количества других приложений.
Какой формат использовать для favicon?
Раньше в качестве основного формата использовали ICO. Особенность данного формата – мульти-размерность. Данный файл может хранить в себе несколько размеров иконки. На смену ICO пришел формат PNG. ICO все еще поддерживаемый, но большинство современных браузеров выбирают PNG формат иконки, который легче. Некоторые браузеры не могут выбрать правильный значок в файле ICO, что приводит к неправильному использования значка с низким разрешением.
О каких платформах пойдет речь в этой статье?
Десктопные браузеры
Начнем, пожалуй, с классического десктопа.
Как было упомянуто ранее, формат ICO сегодня является устаревшим, но это не значит, что про него нужно забыть. Формат ICO может спасти вашу иконку и корректно отображать favicon в некоторых случаях. Например, до 11 версии IE PNG-формат не поддерживается. Поэтому для IE10 и младших версий нужно использовать старый формат ICO. В таком случае желательно использовать следующую комбинацию ICO и PNG форматов:
Для создания мульти-размерной иконки ICO можно использовать сервис-конвертер icoconvert. При генерации иконки необходимо выбрать следующие размеры: 16х16, 32х32, 48х48 (highest resolution icon).
Иконки PNG имеют следующие размеры: 16х16, 32х32, 96х96, 120х120. Зачем иконка 120х120? Яндекс Справка сообщает, что может воспользоваться иконкой данного размера.
Если обратить внимание на значение rel (тип ресурса), то icon – учитывается большинством браузеров, а shortcut icon – учитывается браузером IE.
Chrome на Android
Android ожидает увидеть значок 192х192 в формате PNG, alpha-канал (прозрачность) приветствуется.
Android Chrome полагается на манифест веб-приложения. Любой сайт может использовать манифест для того, чтобы ссылаться на некоторые значки.
Сам файл манифеста формата json и объявляется следующей строкой:
Файл манифеста для Android Chrome можно сгенерировать с помощью сервиса RealFaviconGenerator.
Иконки должны иметь следующие размеры: 72х72, 96х96, 144х144, 192х192, 512х512 в формате PNG, прозрачность приветствуется. Так как иконка может иметь прозрачный фон, то в манифесте можно указать цвет с помощью background_color.
Стоит отметить, что на телефоне пользователь имеет возможность сохранить страницу браузера на главный экран. Это будет просто ссылка на страницу вашего сайта, подтянется иконка с названием android-icon-192×192.png, которая объявлена у вас в коде.
Если же подключить к сайту манифест, то при открытии страницы пользователю может быть предложено сохранить сайт в качестве приложения. В данном случае вы имеет возможность объявить визуально ту же иконку (android-icon-192×192.png) или переделать дизайн иконки для приложения под свои нужды и объявить в манифесте с соответствующими размерами.
Иконка закладки в iOS (PWA)
iOS Safari ожидает увидеть apple touch icon. Это иконка PNG формата 180х180, без alpha-канала (без прозрачности). Углы иконки будут автоматически скруглены, что упрощает создание apple touch icon.
Пользователи iOS также могут добавить сайт на главный экран, и он будет выглядеть как приложение. Такая ссылка отображается в виде значка и называется Web Clip.
Нижеперечисленные размеры иконок предназначены для поддержки различных устройств, например, для iPhone и iPad:
В коде нужно добавить атрибут rel=«apple-touch-icon» и указать размер с помощью sizes.
Если на сайте нет значка, размер которого является рекомендованным для устройства, то будет использована сама близкая по размеру иконка большего размера. Основная apple touch icon это иконка размером – 180х180. Остальные устройства могут уменьшать иконку.
При создании иконки не забывайте об отступах. Они должны быть не менее 4px со всех сторон. Это необходимо, чтобы ваша иконка не обрезалась, так как значок приложения в iOS имеет скругленные углы.
Следует отметить, что устройства под iOS не единственные, которые ищут apple touch icon. Некоторые браузеры, вроде Android Chrome, могут использовать apple touch иконки, так как они встречаются чаще других PNG иконок высоких разрешений.
macOS
В Mac OS дела обстоят совершенно иначе. Если пользователь попробует сохранить сайт на рабочий стол, то вместо иконки сайта будет отображен скриншот страницы.
Чтобы добавить иконку необходимо использовать формат SVG, который позволит сделать маску иконки. Данная иконка будет отображена при закреплении вкладки в Safari.
В коде нужно добавить атрибут rel=«mask-icon». Сама SVG-иконка должна быть черного цвета. Цвет иконки задается в атрибуте color=»#e52037″.
SVG-иконка используется в закрепленной вкладке (pinned tab – no focus) в монохромном виде. При наведении (pinned tab – focus) иконка будет закрашена в цвет, который имеет атрибут «color». В touch bar также передается цвет атрибута «color».
При создании иконки необходимо убрать все имеющиеся тени, сделать ее плоской и простой. Упростить иконку до одного объекта можно с помощью операций «Union» и «Flatten». Данные операции легко применить в программе Figma.
Если закрыть глаза на создание иконки-маски, то браузер просто отобразит первую букву домена вашего сайта.
Windows
С Windows нужно немного запариться, чтобы сделать хорошо.
Для IE10 и более младших версий необходимо использовать формат ICO, так как до IE11 формат PNG не поддерживался.
С приходом IE11 и Windows 8.1 появилась возможность закреплять сайты в виде живых плиток. Для маленьких плиток используется по умолчанию favicon, а для больших и широких плиток необходимо задавать изображение конкретного размера. Это можно сделать с помощью добавления тегов метаданных в разметку сайта или создать browserconfig.xml (файл конфигурации браузера).
Пример добавление тегов метаданных в разметку веб-сайта для больших плиток:
Данной строкой мы указываем цвет фона плитки:
Можно указать имя вашего веб-сайта:
Что такое browserconfig? Это XML-документ, в котором перечислены различные значки, соответствующие пользовательскому интерфейсу Metro UI.
Чтобы подключить файл browserconfig в разметке необходимо добавить следующую строку в head:
Сам файл будет выглядеть следующим образом:
В browserconfig файле определены изображения для различных размеров плитки.
Microsoft рекомендует брать больший размер изображений в целях поддержки экранов с высокой плотностью пикселей.
В следующем списке приведены некоторые рекомендации по использованию различных размеров:
Подготовка favicons
Перед тем как добавлять ваши иконку в корневую папку сайта необходимо их подготовить. Исходные размеры иконок не очень большие, но можно их сжать с наименьшей потерей качества.
Например, в моем случае вес всех изображений был 200кб, после сжатия 50кб. Качество изображений практически не изменилось. Вы можете воспользоваться любым удобным сервисом для сжатия картинок. Я использовала iloveimg.
Заключение
Последовательность подключения в разметке веб-сайта:
С помощью последней строки кода «theme-color» можно закрасить адресную строку и строку уведомлений в любой цвет. В значении content задается цвет.
Для проверки иконок вашего сайта воспользуйтесь RealFaviconGenerator. Данный сервис покажет, как отображаются ваши иконки на разных платформах, подскажет где и какие могут быть проблемы.
Кроме того, данный сервис может сгенерировать необходимые размеры, форматы иконок и код. Но необходимо проверять исходники на наличие всех рекомендуемых размеров для корректного отображения на различных устройствах.
How To Add a Favicon to Your Website with HTML
In this tutorial, we will walk through the steps involved in adding a favicon to your webpage using HTML. You can use any image you like for your favicon, but keep in mind that simple, high-contrast images often work best given the favicon’s small size. You can also generate a custom favicon through sites like favicon.cc.
A favicon is a small image that is located in the browser tab to the left of a webpage’s title. The image below illustrates the location of a favicon.
To add a favicon to your site, create a folder in your project directory called images (if you don’t already have one) and save your desired favicon image in this folder. If you don’t have an image, you download this Sammy the Shark image that we have hosted on our demonstration website. (For a refresher on how to add images to webpages using HTML, please visit our tutorial HTML Images from earlier in this tutorial series.
Make sure to replace Favicon_Image_Location with the relative file path of your favicon image. Save the index.html file and reload it in your web browser. Your browser tab should now contain a favicon image.
You should now know how to add favicon images to websites using HTML.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Tutorial Series: How To Build a Website with HTML
This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior coding experience is necessary but we recommend you start at the beginning of the series if you wish to recreate the demonstration website.
At the end of this series, you should have a website ready to deploy to the cloud and a basic familiarity with HTML. Knowing how to write HTML will provide a strong foundation for learning additional front-end web development skills, such as CSS and JavaScript.
How to Add a Favicon to Your Website with HTML
KB Home | Web Development | How to Add a Favicon to Your Website with HTML
Introduction
Users no longer read text on a website but skim through its content. As a result, businesses need to articulate their concepts and identity visually.
Favicons allow users to identify websites at a glance. They create a consistent browsing experience and reinforce a sense of trust. A website or ecommerce store without a favicon may appear unprofessional and unreliable.
Find out how to add a favicon to your website using HTML.
What is a Favicon?
A favicon is a small square image that represents a website or web page. Browsers display favicons to help users access and navigate multiple sites more easily. Favicons appear in:
Favicons also serve as shortcut icons if a user pins web pages on the home screen of a mobile device.
Add a Favicon in HTML
To add a favicon using HTML:
Step 1: Create a Favicon
Due to its small size, a favicon needs to be simple and direct. Do not add intricate details or embellishments. When designing a favicon, consider using:
The most common favicon formats include:
A favicon needs to work on different browsers and maintain image quality on various devices. To get the best possible results, you need to create a favicon in several sizes. The following image sizes are essential for achieving cross-browser compatibility:
Utilize a favicon generator to avoid creating images manually. These free tools automatically create favicons in the correct format and all applicable sizes.
Step 2: Upload Favicon
Use an FTP Client or cPanel to upload the favicon ICO or PNG files to the website’s root directory.
It is recommended but not mandatory to place favicon files in the root directory. If the images are in a different directory, you can use the HTML tag to specify the image file location
Most browsers, bots, and automated scripts still check the favicon.ico file in the website’s root by default.
Step 3: Add Link to HTML
To explicitly point browsers to the location of the favicon files, place tags within the HTML tag.
The tag and its attributes tell browsers and devices which image to use and where to find it. In this example the PNG images are in the root directory:
Edit the attribute values to reflect the values on your system:
The HTML can contain multiple tags. The type and sizes attributes allow browsers to select the appropriate icon.
Step 4: Test on Multiple Browsers
Use a browser to access the website and verify that the favicon displays properly. Check the tab image, bookmark the page, access the browsing history, etc.
Test the favicon in several browsers, change backgrounds, view modes, and devices to see if the quality or visibility of the favicon is affected.
Best Favicon Generators
Favicon generators help users design and create favicons. These web-based tools convert image templates into the correct format, provide multiple image sizes, and generate device-specific favicons.
Some of the most popular and free favicon generators include:
1. RealFaviconGenerator
The RealFaviconGenerator allows users to upload an image and tweak the favicon for different browsers and devices.
The on-screen previews provide valuable insights and tips on making your favicon as effective as possible on various platforms.
RealFaviconGenerator also has a Favicon Checker feature. By entering the website’s URL, you receive a detailed analysis of the favicon’s quality on various platforms. Use this feature to save time when troubleshooting or testing favicons.
2. Favicon.io
The favicon.io generator allows you to upload a PNG or generate a favicon from custom text. The system converts the templates into the proper format and provides all the necessary files and HTML links.
The interface is user-friendly, with clear on-screen instructions. Most actions are completed by dragging and dropping files.
Favicon.io also provides the option to create favicons from emojis.
3. Genfavicon
Genfavicon is a straightforward tool that allows you to cut and crop an image and see a preview on the page before downloading.
The options regarding sizes and format are limited, but this tool is useful for quickly preparing and editing an image before conversion.
4. Faviconr
The Faviconr generator is a lightweight solution that converts images into a favicon.ico file.
Websites that do not need optimized images for every possible platform can use Faviconr and set up a basic favicon in a matter of minutes
5. X-Icon Editor
The X-Icon Editor is ideal for users that want to create a high-resolution favicon from scratch.
This tool also enables users to upload images, crop them to predefined sizes, and preview the favicon before downloading the file.
Conclusion
You have created and added a favicon to your website using HTML. The favicon is optimized for multiple browsers and platforms.
If you have an ecommerce store, adding a favicon shows that your website values its users and actively works to improve their experience.
How to add a browser tab icon (favicon) for a website?
I’ve been working on a website and I’d like to add a small icon to the browser tab.
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
There are actually two ways to add a favicon to a website.
Simply add the following code to the element:
favicon.ico in the root directory
So all you have to do is to make the /favicon.ico request to your website return your favicon. This option unfortunately doesn’t allow you to use a PNG icon.
The best one that I found is http://www.favicomatic.com/ I say best because it gave me the crispest favicon, and required no editing after their transformation. It will generate favicons at 16×16 and 32×32 and to quote them «Every damn size, sir!» Also, their site looks cool and is easy to use.
They also generate the html that you need to use for the files they generate.
I looked at the first 20 or so google results, and this was by far the best.
There are a number of different icons and even splash screens that you can set for various devices. This answer goes through how to support them all.
Here are some snippets I have used with relevant links to where I gathered the information. See my blog for more information and more information about the ASP.NET MVC Boilerplate project template with all this built in right out of the box (Including sample image files).
Add the following mark-up to your html head. The commented out sections are entirely optional. While the uncommented sections are recommended to cover all icon usages. Don’t be scared, most if it is comments to help you.
My browserconfig.xml file. Full explanation above.
My manifest.json file. Full explanation above.
A list of the files in the project (Note that the names of these files are important if you decide to put some of them at the root of your project to avoid using the above meta tags):
Total Overhead
If you take out the comments that’s 3KB of extra HTML, if you don’t support splash screens that’s 1.5KB. If you are using GZIP compression on your HTML content, which everyone should be doing these days, that leaves you with about 634 Bytes of overhead per request to support all platforms or 446 Bytes without splash screens. I personally think its worth it to support IOS, Android and Windows devices but its your choice, I’m just giving the options!
Side Note About The Current Web Icon/Splash Screen/Settings Situation
This situation with vendor specific icons, splash screens and special tags to control the web browser or pinned icons is ridiculous. In a perfect world we would all use a favicon.svg file which could look good at any size and could be placed at the root of the page. Only FireFox supports this at the time of writing (See CanIUse.com).
However, icons are not the only setting these days, there are several other vendor specific settings (shown above) but a favicon.svg file would cover most use cases.
Update
Updated to include the new Android/Chrome version M39+ favicon/theming options. Interestingly, they have gone with a similar approach to Microsoft but are using a JSON file instead of XML.
Adding a favicon to a static HTML page
I have a few static pages that are just pure HTML, that we display when the server goes down. How can I put a favicon that I made (it’s 16x16px and it’s sitting in the same directory as the HTML file; it’s called favicon.ico) as the «tab» icon as it were? I have read up on Wikipedia and looked at a few tutorials and have implemented the following:
Update
I could not get this to work locally although the code checks out it will only really work properly once the server started serving the site. Just try pushing it up to the server and refresh your cache and it should work fine.
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Most browsers will pick up favicon.ico from the root directory of the site without needing to be told; but they don’t always update it with a new one right away.
However, I usually go for the second of your examples:
Actually, to make your favicon work in all browsers, you must have more than 10 images in the correct sizes and formats.
I created an App (faviconit.com) so people don´t have to create all these images and the correct tags by hand.
Hope you like it.
This table shows how to use the favicon in major browsers. The standard implementation uses a link element with a rel attribute in the document’s section to specify the file format and filename/location.
Note that most browsers will give precedence to a favicon.ico file located in the website’s root (therefore ignoring any icon link tags).
File format support
The following table illustrates the image file format support for the favicon :
Browser Implementation
The table below illustrates the different areas of the browser where favicon’s are displayed:
Icon files can be 16×16, 32×32, 48×48, or 64×64 pixels in size, and 8-bit, 24-bit, or 32-bit in color depth.
While the information above is generally correct, there are some variations/exceptions in certain situations.
See more detailed information at the source on Wikipedia.
Update: («more info»)
You can retrieve (programmatically or manually) Google’s cached favicon for any domain with a URL such as: https://www.google.com/s2/favicons?domain=stackoverflow.com
Using the above URL directly in an tag returns: » «.
Convert your image file to Base64 string with a tool like this and then replace the YourBase64StringHere placeholder in the below snippet with your string and put the line in your HTML head section:
This will work 100% in browsers.
As recommended by W3.org, you can use the rel attribute to achieve this.
If the favicon is a png type image, it’ll not work in older versions of Chrome. However it’ll work just fine in FireFox. Also, don’t forget to clear your browser cache while working on such things. Many a times, code is just fine, but cache is the real culprit.
This worked for me
I know its older post but still posting for someone like me. This worked for me
put your favicon icon on root directory..
As per OP’s update, It was not showing up locally, but as per OP’s update, once I uploaded it to the server, it was fine.
Since this is a simple, static html website, I have the luxury of working on it without running a local webserver.
A webserver will generally automatically serve up the favicon, if there is one, by default.
But when not running a webserver, the browser itself will not just read the directory looking for additional files, say a favicon.ico, unless it is listed in the html document.
So, while I had the following items in the head tag:
Once I added the following line:
It did also show up in my browser, when I viewing the local file, even when not serving it through a local server.
So icon showed up fine when it ran on the live server, but not locally.
Источники информации:
- http://www.digitalocean.com/community/tutorials/how-to-add-a-favicon-to-your-website-with-html
- http://ccbill.com/kb/favicon-html
- http://stackoverflow.com/questions/4888377/how-to-add-a-browser-tab-icon-favicon-for-a-website
- http://stackoverflow.com/questions/9943771/adding-a-favicon-to-a-static-html-page