- Добавляем иконки сайта для iPhone, iPad и Android
- Если Ваш сайт достаточно популярен, то многие пользователи заходят на него даже с телефонов и планшетов! Многие добавляю его в закладки на рабочий стол телефона или планшета, для того чтобы на рабочем столе отображалась красивая иконка вашего сайта, необходимо.
- Для быстрого автоматического создания иконок для сайта
- Use Apple touch icon
- Use Apple touch icon ( apple-touch-icons )
- Why is this important?
- What does the hint check?
- Examples that trigger the hint
- Examples that pass the hint
- How to use this hint?
- Мета-теги HTML для Apple Safari
- Apple Touch Icon
- Apple Touch Icon Precomposed
- Mask Icon
- Apple-Mobile-Web-App-Title
- Apple-Mobile-Web-App-Capable
- Apple-Mobile-Web-App-Status-Bar-Style
- Apple-Itunes-App
- Format-Detection
- Какие нужны фавиконки
- Safari Web Content Guide
- Configuring Web Applications
- Specifying a Webpage Icon for Web Clip
- Specifying a Launch Screen Image
- Adding a Launch Icon Title
- Hiding Safari User Interface Components
- Changing the Status Bar Appearance
- Linking to Other Native Apps
Добавляем иконки сайта для iPhone, iPad и Android
Если Ваш сайт достаточно популярен, то многие пользователи заходят на него даже с телефонов и планшетов! Многие добавляю его в закладки на рабочий стол телефона или планшета, для того чтобы на рабочем столе отображалась красивая иконка вашего сайта, необходимо.
Если Ваш сайт достаточно популярен, то многие пользователи заходят на него даже с телефонов и планшетов!
Многие добавляю его в закладки на рабочий стол телефона или планшета, для того чтобы на рабочем столе отображалась красивая иконка вашего сайта, необходимо:
Первым делом, нам необходимо создать нужную иконку в формате .png. Рисуете (или подбираете) ее. Желательно, в хорошем разрешении.
Качество (разрешение) экранов устройств от Apple постоянно растет и меняется, поэтому нужно оптимизировать эти «картинки» под разные устройства.
Второе, необходимо сделать иконки разных размеров для разных устройств:
для старых iPhone размер иконки должен быть 57х57, для новый, начиная с 4-го действуют следующие размеры:
- 60х60 — IPhone
- 76×76 -iPad
- 120×120 — iphone-retina
- 152×152 — ipad-retina
Третье, вставить в код указав пути к картинкам:
Safari на iOS 7 не добавляет эффекты к иконкам. А старые версии Safari добавляли эффекты для иконок , чтобы эффект не применялся — нужно к именам файлам добавить —precomposed.png
А что Android.
Все дело в том, что Android-девайсы также подхватывают файлы apple-touch-icon.png и несмотря на наличие в названии слова «apple» 🙂
Справедливости ради, хочу заметить, что ОС Android намеренно не ищет эти иконки, а только в том случае, если пользователь решил добавить сайт на «рабочий стол».
В заключении — если не хотите заморачиваться со вставкой кода, подготовкой картинок разного размера, то просто закиньте в корень сайта картинку (размером 60 на 60 пикселей) с названием «apple-touch-icon.png». Это самый простейший способ.
Для быстрого автоматического создания иконок для сайта
Мы советуем использовать сервис ICONOGEN
Укажите файл с иконкой и сервис быстро сделает иконки разных размеров:
Файлы можно скачать архивом.
Сервис так же генерирует html код для вставки в шаблон сайта:
Источник
Use Apple touch icon
Development flow integration
Use Apple touch icon ( apple-touch-icons )
apple-touch-icons requires that at least one Apple touch icon is present and of a standard size.
Why is this important?
Since iOS 1.1.3 , Safari for iOS has supported a way for developers to specify an image that will be used to represent the web site or app on the home screen. The image is known as the touch icon.
Per Apple’s current guidance, default touch icon sizes are as follows:
Device or context | Icon size |
---|---|
iPhone | 180px × 180px (60pt × 60pt @3x) |
iPhone (X/Plus) | 120px × 120px (60pt × 60pt @2x) |
iPad Pro | 167px × 167px (83.5pt × 83.5pt @2x) |
iPad, iPad mini | 152px × 152px (76pt × 76pt @2x) |
Not declaring the touch icon in the page and having it in the root of the site is not recommended, as Apple may change what is requested by default.
In older versions of Safari for iOS, the precomposed keyword could be used to prevent iOS from adding different visual effects to the touch icon (i.e., rounded corners, drop shadow, reflective shine). Starting with iOS 7, no special effects are applied to touch icons, so there is no need to use the precomposed keyword anymore.
When using one image, there is no need to use the sizes attribute.
As of iOS 11.1.0 , Safari for iOS supports the web app manifest file which provides a standard, cross-browser way of defining, among other, the icons browsers can use in various contexts (home screen, application menu, etc.). However, Safari ignores the icons defined in the web app manifest and still uses the non-standard apple-touch-icon .
What does the hint check?
The hint checks if one or more apple-touch-icon declarations exist in the , and:
- each has rel=»apple-touch-icon»
- each declared image is accessible (e.g., doesn’t result in a 404 ),
- each declared image is a PNG of one of the resolutions specified above
Examples that trigger the hint
No apple-touch-icon was specified:
The apple-touch-icon is not specified in :
The apple-touch-icon has a rel attribute different than apple-touch-icon :
The apple-touch-icon is not accessible:
Response for apple-touch-icon.png :
The apple-touch-icon is not a PNG file:
One or more apple-touch-icon files is not a recommended size:
Examples that pass the hint
How to use this hint?
This package is installed automatically by webhint:
To use it, activate it via the .hintrc configuration file:
Note: The recommended way of running webhint is as a devDependency of your project.
Источник
Мета-теги HTML для Apple Safari
Обзор html мата-тегов для браузеров Safari на платформах Mac OS X и iOS.
Apple Touch Icon
Иконка сайта в iOS на экране закладок и домашнем экране.
Иконки разных размеров указываются атрибутом sizes :
Apple Touch Icon Precomposed
Тоже самое что и apple touch icon , но с наложенными эффектами в стиле iOS с закругленными углами и т.д.
Mask Icon
Используется в MacOS при сохранении сайта на рабочий стол. Элементы SVG должны быть черного цвета, цвет задается атрибутом color .
Apple-Mobile-Web-App-Title
При добавлении сайта на домашний экран в iOS задает имя иконки.
Apple-Mobile-Web-App-Capable
В Safari iOS для закрепленных сайтов на экране «Домой» включает полноэкранный режим.
Apple-Mobile-Web-App-Status-Bar-Style
Задает стиль панели состояния при полноэкранном режиме.
Может иметь следующее значение:
default | Белый фон |
black | Черный фон |
black-translucent | Прозрачный фон и белый цвет иконок и шрифтов |
| | |
Apple-Itunes-App
В iOS Safari выводит баннер с приложением в App Store.
Баннер не отобразится, если устройство не поддерживает приложение или оно недоступно для данной локали, подробнее на developer.apple.com.
Format-Detection
В iOS запрещает распознавать номера телефонов и адреса.
Источник
Какие нужны фавиконки
30 августа 2017
Фавиконка — это favorite icon, то есть иконка для избранного. Её придумали для IE5 в 99 году, чтобы у сайтов была узнаваемая картинка. Достаточно было бросить в корень сайта файл favicon.ico и браузер сразу её подхватывал и делал красиво. До сих пор все браузеры делают запрос в корень сайта и пытаются найти там файл в формате ICO. Бросил и забыл, расходимся? Рано!
Долгое время всё прекрасно работало. В контейнер ICO можно было зашить много разных иконок: от крошечной монохромной до огромной полупрозрачной. Браузер после скачивания иконки сам выбирал нужный формат. Проблема была в том, формат ICO страшно неэффективный. Если зашить в ICO две PNG-иконки 16 и 32, то иконка будет весить в два-три раза больше, чем исходные файлы. Браузерам приходилось тянуть не только ненужные форматы, но ещё и в неэффективном виде.
Но ICO признали все браузеры и научились подключать его не только из корня сайта, но и из произвольного места. Если указать в голове документа
, то браузер пойдёт не в корень, а туда, куда вы ему показали. Линковать особый адрес приходилось на каждой странице, но это же не проблема — иконка ведь всего одна! Ну правда, что могло пойти не так? Так и жили.
При отсутствии внятных стандартов, за дело взялась Apple. К первому Айфону прилагался прорывной мобильный браузер Safari, который тоже начал искать в корне сайта иконки, но на этот раз в формате PNG и с названием apple-touch-icon. Эту иконку видно в избранном и при добавлении сайта на домашний экран. Бросил в корень второй файл и забыл, расходимся? Нет.
Чтобы иконка была без блика сверху, нужен файл apple-touch-icon-precomposed, ещё один для ретины, потом ещё несколько для всех моделей Айпадов, тройной ретины… и в итоге вам нужно намусорить в корне или в шапке сайта целым ворохом иконок со специальными размерами: 72, 76, 114, 120, 144, 152, 180 и кажется что-то ещё. Чтобы разобраться во всех нюансах тач-иконок, читайте отличное руководство Матиаса Байненса.
Иконки Apple в какой-то момент стали стандартом де-факто. Их начали подтягивать не только другие браузеры, но и другие сервисы, чтобы сделать иконку для вашего сайта. Проблема была в том, что это было слабо документировано, учитывало интересы только одной компании и несло само её имя в формате. Нужен был стандарт.
В HTML5 появилось расширенное описание
: добавился атрибут sizes , чтобы указывать размеры, и атрибут type , чтобы указывать формат иконки. Например, если у вас ICO с несколькими иконками внутри, то укажите все размеры через пробел в sizes . Если иконка векторная — да, так тоже можно — укажите размер any . Главное, не забудьте указать правильные типы. Теперь-то расходимся, проблема решена? Почти.
Для каждой иконки писать свой линк? Сложно! А если хочется фирменный цвет указать, заставку или какие-то особенности работы всего сайта? Не иконками едиными. Вот бы нам конфиг в отдельном файле! Было и такое: browserconfig.xml для плиточных иконок IE11, JSON-манифест для иконок-виджетов табло Яндекс Браузера. Экспериментов было много, но теперь есть и стандартное решение — веб-манифест.
Спецификация Web App Manifest описывает простой JSON-файл, в котором можно указать не только все иконки, их размеры и форматы, но и полностью описать ваш сайт или приложение. Фирменный цвет, цвет фона, язык и направление письма, полное и краткое название, ориентация, режим запуска и другое. Вы подключаете его с помощью
на каждую страницу и браузер сразу всё знает. Хороший инспектор манифеста есть во вкладке Application отладчика Chrome.
А что Apple? Что-что… До сих пор поддерживает свой формат тач-иконок и придумала даже ещё один: новый, нестандартный, как мы любим! С помощью
для закреплённых вкладок Safari и кнопок на тач-баре Макбуков можно указать монохромную векторную маску и цвет для наведения. Спасибо, конечно, за вектор, но неспасибо за очередной велосипед.
Веб-манифест уже так или иначе поддерживают Chrome, Opera, Samsung Internet и Firefox, но пока только на Андроиде. В Edge он тоже скоро появится — разработка в процессе. Пока это будущий способ подключения иконок, а что делать сегодня, вот прямо сейчас? Сочетать всё, что мы знаем.
Для начала, забудьте про ICO, если только вам не нужен IE10. Подключите линком PNG-иконки: простую на 16 и 32 для ретины, чтобы было красиво в браузерной строке и закладках. Дальше подключите линком из корня сайта apple-touch-icon.png размером 180 × 180. Потом подключите веб-манифест, в котором указана иконка на 192 для Андроида. Ну и можно там же упомянуть 16, 32, вектор, цвета и название — пригодится.
Этого вам должно хватить, чтобы было красиво в основных современных браузерах. Но если нужно упороться по мелочам и сделать вот прямо идеально на каждой платформе — мои соболезнования и читайте документацию в описании к видео. Есть ещё сносный онлайновый генератор иконок, но я бы не доверил ему генерировать графику — будет мыльно. А вот код позаимствовать можно.
Ну что, чуда не произошло и всё по-старому: мусор в шапке, мусор в корне? Знаете, нет, я верю, что со временем веб-манифест наведёт порядок, поэтому подключайте его уже сегодня. Вот выбросим мусор и заживём!
Источник
Safari Web Content Guide
Configuring Web Applications
A web application is designed to look and behave in a way similar to a native application—for example, it is scaled to fit the entire screen on iOS. You can tailor your web application for Safari on iOS even further, by making it appear like a native application when the user adds it to the Home screen. You do this by using settings for iOS that are ignored by other platforms.
For example, you can specify an icon for your web application used to represent it when added to the Home screen on iOS, as described in Specifying a Webpage Icon for Web Clip . You can also minimize the Safari on iOS user interface, as described in Changing the Status Bar Appearance and Hiding Safari User Interface Components , when your web application is launched from the Home screen. These are all optional settings that when added to your web content are ignored by other platforms.
Read Viewport Settings for Web Applications for how to set the viewport for web applications on iOS.
Specifying a Webpage Icon for Web Clip
You may want users to be able to add your web application or webpage link to the Home screen. These links, represented by an icon, are called Web Clips. Follow these simple steps to specify an icon to represent your web application or webpage on iOS.
To specify an icon for the entire website (every page on the website), place an icon file in PNG format in the root document folder called apple-touch-icon.png
To specify an icon for a single webpage or replace the website icon with a webpage-specific icon, add a link element to the webpage, as in:
In the above example, replace custom_icon.png with your icon filename.
To specify multiple icons for different device resolutions—for example, support both iPhone and iPad devices—add a sizes attribute to each link element as follows:
The icon that is the most appropriate size for the device is used. See the “Graphics” chapter of iOS Human Interface Guidelines for current icon sizes and recommendations.
If there is no icon that matches the recommended size for the device, the smallest icon larger than the recommended size is used. If there are no icons larger than the recommended size, the largest icon is used.
If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon. prefix. For example, if the appropriate icon size for the device is 58 x 58, the system searches for filenames in the following order:
Note: Safari on iOS 7 doesn’t add effects to icons. Older versions of Safari will not add effects for icon files named with the -precomposed.png suffix. See First Steps: Identifying Your App in iTunes Connect for details.
Specifying a Launch Screen Image
On iOS, similar to native applications, you can specify a launch screen image that is displayed while your web application launches. This is especially useful when your web application is offline. By default, a screenshot of the web application the last time it was launched is used. To set another startup image, add a link element to the webpage, as in:
In the above example, replace launch.png with your startup screen filename. See the “Graphics” chapter of iOS Human Interface Guidelines for current launch screen sizes and recommendations.
Adding a Launch Icon Title
On iOS, you can specify a web application title for the launch icon. By default, the tag is used. To set a different title, add a meta tag to the webpage, as in:
In the above example, replace AppTitle with your title.
Hiding Safari User Interface Components
On iOS, as part of optimizing your web application, have it use the standalone mode to look more like a native application. When you use this standalone mode, Safari is not used to display the web content—specifically, there is no browser URL text field at the top of the screen or button bar at the bottom of the screen. Only a status bar appears at the top of the screen. Read Changing the Status Bar Appearance for how to minimize the status bar.
Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.
You can determine whether a webpage is displaying in standalone mode using the window.navigator.standalone read-only Boolean JavaScript property. For more on standalone mode, see apple-mobile-web-app-capable .
Changing the Status Bar Appearance
If your web application displays in standalone mode like that of a native application, you can minimize the status bar that is displayed at the top of the screen on iOS. Do so using the status-bar-style meta tag.
This meta tag has no effect unless you first specify standalone mode as described in Hiding Safari User Interface Components . Then use the status bar style meta tag, apple-mobile-web-app-status-bar-style , to change the appearance of the status bar depending on your application needs. For example, if you want to use the entire screen, set the status bar style to translucent black.
For example, the following HTML sets the background color of the status bar to black:
For more on status bar appearance, see the “UI Bars” chapter of iOS Human Interface Guidelines .
Linking to Other Native Apps
Your web application can link to other built-in iOS apps by creating a link with a special URL. Available functionality includes calling a phone number, sending an SMS or iMessage, and opening a YouTube video in its native app if it is installed. For example, to link to a phone number, structure an anchor element in the following format:
For a complete look of these capabilities, see Apple URL Scheme Reference.
Copyright © 2016 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2016-12-12
Источник