In this article we will look at what browser prefixes are, the reasons for their appearance and how to use them in CSS.
What are prefixes?
A web developer starting to learn the theoretical basics of CSS and using this knowledge in practice may run into problems when looking at real-world examples. This may cause him a lack of understanding of what is happening and discourage further desire to study this technology.
For example, when considering the styles of a website, a web developer may encounter properties that contain some obscure words in front: -webkit-, -moz-, -ms-, etc.
* (-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;)
What is it? In fact, everything is simple, these obscure words are prefixes of the following browsers:
- -webkit-: browsers Chrome, Safari, Opera;
- -moz-: Mozilla Firefox browser;
- -ms-: Internet Explorer browser.
Thus, if the name of the property is prefixed, this means that this property is implemented and will be used exclusively in the specified browser. All other browsers will ignore this property. for them, this prefix is \u200b\u200bunknown.
Reasons for the appearance of prefixes?
There were a lot of reasons for the appearance of prefixes:
- For inclusion in the browser of experimental CSS properties that are not yet approved by the standard. Thus, browser makers test and make suggestions before approving CSS properties in the standard.
- To solve problems with cross-browser compatibility.
- To create your own properties that are not part of the CSS standard, but may appear in it after a while.
When an experimental property is approved in the standard and passed testing in the browser, the prefix is \u200b\u200busually removed from it.
How to use prefixes?
Consider the following code as an example:
* (-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;)
This code uses CSS properties that change the algorithm for calculating the width and height for all elements of a web page. The first CSS property -webkit-box-sizing with a value of border-box is intended for browsers that use the webkit (Safari) or blink engine (Chrome, Opera, Yandex.Browser). The second CSS property -moz-box-sizing with a value of border-box is intended for browsers using the Gecko engine (Mozilla Firefox). The last CSS property is intended for browsers in which this property has already been tested and implemented in accordance with the standard.
When using prefixes for CSS properties, remember that they should be placed before the CSS property without a prefix. Why is this so important? This is important because if once the original property (without a prefix) is implemented in the browser, then it will be used (since it is the last one), and not its experimental version.
For example: applying a CSS property to all elements of a webpage in Google Chrome version 40.
The figure above shows that the original box-sizing property is already embedded in this browser, and due to the fact that it is the last one, the browser uses it instead of the above -webkit-box-sizing property.
How to check support for a specific property in a browser?
A site on which you can check whether this property is implemented or not in a specific browser can be the link below. In addition, the site shows the percentage of users who use this version of the browser.
Website "Can I Use ..."For example: check how the transform property is implemented in browsers.
On the CanIUse website, browsers are marked in different colors, depending on the state in which support for certain properties or tags is located:
- The red rectangle is a browser in which this property is not implemented;
- A green rectangle with a hyphen in the upper right corner is a browser in which this property is used through a prefix;
- A light green rectangle is a browser in which this property is partially implemented;
- The green rectangle is the browser in which this property is implemented in accordance with the standard.
As you know, not all browsers treat css style files the same way. Basically, problems arise with old versions of small-scale creation Internet explorer (Version 7 and below). By the way, if the problem occurs in modern browsers (like Opera, Mozilla Firefox, Chrome), then I highly recommend revise page layout.
So here. There is a problem with browsers. And I know at least three ways to solve this problem.
1st method. The most correct
Styles for browsers that do not correctly understand your css are written in a separate file. Usually this browser, as I said, is Internet explorer, and these files are called fix-ie.css
... ... ...
Change name Themesto the real name of your topic - and when you open Internet explorer version 7 and below - this file will be added to the general set of style files, and even cached if caching is enabled.
This line is responsible for the browser version to which the stylesheet will be connected:
где styles.css - файл, который будет отвечать за стили только для IE .
Единственный известный на данный момент способ написать стили только для Google Chrome , используя при этом JavaScript . При этом не нужно знать JS , достаточно взять пример отсюда и адаптировать его под свои нужды.
Суть состоит в том, что мы проверяем, каким браузером пользуется посетитель сайта и если это Google Chrome , то подключаем для него дополнительный файл стилей, в котором нужные свойства, которые могут перекрываться в основном файле стилей, выделяем !important .
раздел, добавляем такие строчки, внутри тега ):
var isChrome = !!window.chrome && !!window.chrome.webstore; if (isChrome) { var $ = document; var cssId = "myCss"; var head = $.getElementsByTagName("head"); var link = $.createElement("link"); link.id = cssId; link.rel = "stylesheet"; link.type = "text/css"; link.href = "/css/template.css"; //путь к файлу стилей только для Chrome link.media = "all"; head.appendChild(link); }
Единственный известный на данный момент способ написать стили только для Opera , используя при этом JavaScript . При этом не нужно знать JS , достаточно взять пример отсюда и адаптировать его под свои нужды.
Суть состоит в том, что мы проверяем, каким браузером пользуется посетитель сайта и если это Opera , то подключаем для него дополнительный файл стилей, в котором нужные свойства, которые могут перекрываться в основном файле стилей, выделяем !important .
Синтаксис такой(в файле.php или.html , куда подключаем файл стилей,т.е. в
раздел, добавляем такие строчки, внутри тега ):var isOpera = !!window.opera || /opera|opr/i.test(navigator.userAgent); if (isOpera) { var $ = document; var cssId = "myCss"; var head = $.getElementsByTagName("head"); var link = $.createElement("link"); link.id = cssId; link.rel = "stylesheet"; link.type = "text/css"; link.href = "/css/template.css"; //путь к файлу стилей только для Opera link.media = "all"; head.appendChild(link); }
Единственное что вам тут нужно поменять это в 10 строчке путь до вашего файла стилей.
Спасибо всем за внимание, рады для вас стараться. Повторимся, что мы ждем ваших комментариев, предложений по улучшению и т.д.
6.5KКроссбраузерность — это способность сайта корректно отображаться в различных браузерах. Ресурс должен работать одинаково во всех версиях обозревателей.
Особенно это важно в эпоху адаптивного веб-дизайна, когда на первый план выходит способность front-end адаптироваться к широкому диапазону различных устройств и при этом обеспечивать оптимальное качество просмотра.
Раньше дизайнер создавал макет дизайна в Photoshop , который затем переносился в HTML и CSS . На сегодняшний день технологические изменения заставляют переосмыслить эту концепцию. Мы больше не можем предсказать, какой браузер, разрешение или устройство будут использоваться для просмотра сайта. Ушли в прошлое те времена, когда большинство компьютеров использовало фиксированное разрешение 1024 на 768 пикселей, и можно было разрабатывать сайты со статическими размерами.
Современные браузеры полностью поддерживают HTML5 и CSS3 . Но один и тот же код HTML / CSS / JavaScript в старых браузерах интерпретируется по-разному, что приводит к «кроссбраузерной несовместимости » сайта. Особенно это касается старых версий Internet Explorer .
В данной статье мы рассмотрим текущую статистику по просмотрам веб-страниц, приведем перечень средств, которые помогают решать различные проблемы совместимости.
1. Текущая ситуация
Общемировая статистика за 2015 год показывает, что топ-14 используемых разрешений экрана находятся в диапазоне от 1920 на 1080 до 320 на 480 пикселей.
Хотя Windows 7 (31,20% ) до сих пор удерживает большую долю рынка, мобильные платформы начинают заменять традиционные, стационарные.
Взглянув на статистику за 2015 год по используемым браузерам, мы видим, что первое место принадлежит Chrome (все версии — 44,87% ), второе место — Firefox (все версии — 10,37% ), третье Internet Explorer 11 (6,84% ).
Ускоренные темпы выпуска новых версий Google Chrome и Firefox позволяют более эффективно разрабатывать проекты для этих платформ. Немного другая картина складывается для «плохого парня » Internet Explorer , потому что в Сети до сих пор можно найти его старые версии. А это приводит к возникновению проблем с кроссбраузерностью сайта.
Корпорация Microsoft остановила поддержку IE6 8 апреля 2014 года. И с 2016 года будет поддерживаться и получать обновления только самая последняя версия Internet Explorer . Это фактически означает, что в начале 2016 года была полностью прекращена поддержка IE7 и IE8 , независимо от операционной системы. IE9 будет поддерживаться только в Windows Vista , IE10 — только в Windows Server 2012 , IE11 — в Windows 7 и Windows 8.1 :
Как следствие, нужно прекратить разработку под IE6 и, а также под IE7 . Чтобы обосновать эту стратегию, можно привести несколько примеров решений известных компаний: Google прекратила поддержку IE8 в ноябре 2012 года, а IE9 — в октябре 2013 года.
Github больше не поддерживает IE 7 и 8 . Кроме этого часть функционала Twitter не работает в IE8 . И, наконец, популярный фреймворк не будет поддерживать IE8 , начиная с 4 версии .
Тем не менее, статистика использования может варьироваться в зависимости от региона: 6,11% пользователей в Китае в 2015 году по-прежнему просматривали страницы через IE8 . Если принять во внимание, что в Китае было около 724400000 интернет-пользователей, можно понять, что в этом году примерно 44200000 китайцев продолжают использовать IE8 .
Поэтому региональные рынки, специфические клиенты и требования отрасли могут существенно отличаться. Особенно это касается корпоративных и правительственных учреждений.
2. Проанализируйте свою аудиторию
Основной принцип здесь такой: чем выше требуемая кроссбраузерность, тем больше времени потребуется на разработку, что приводит к увеличению стоимости проекта. Чтобы принять взвешенное, экономически обоснованное решение, нужно задать себе следующие вопросы:
- Какова ваша целевая аудитория?
- На какой географический регион нужно настроить таргетинг?
- Какие браузеры и устройства используют ваши посетители?
- Существуют ли в компании или отрасли технические факторы, которые заставляют вас поддерживать конкретные версии старых браузеров?
- Каковы с точки зрения электронной коммерции коэффициенты конверсии и рентабельности различных групп пользователей по версиям браузеров?
Ответив на эти вопросы с помощью статистических данных, например, из Google Analytics , можно получить объективную картину.
3. Проблемы в устаревших браузерах и различные подходы к разработке
Адаптивный веб-дизайн во многом зависит от медиа-запросов, с помощью которых изменяется CSS
для различных разрешений экрана. Кроме этого современные сайты характеризуются использованием семантических элементов HTML5
(например,
Это подводит нас к следующим техническим сложностям при реализации CSS кроссбраузерности:
- Медиа-запросы CSS3
- Семантические элементы HTML5 : не поддерживается в IE6 , 7 и 8 ;
- Селекторы CSS3 : не поддерживается в IE6 . Только частично поддерживаются в IE7 и 8 ;
- Единицы REM : не поддерживается в IE6 , 7 и 8 . Только частично поддерживаются в IE9 и 10 ;
- Лимит количества правил CSS : IE9 и ниже поддерживают только 4095 CSS-селекторов . Правила после 4095-ого селектора не применяются.
Указанные выше ошибки будут иметь наибольшее влияние на стратегию, применяемую при реализации адаптивного дизайна.
Существуют две основных стратегии разработки: постепенное упрощение и прогрессивное улучшение .
Прогрессивное улучшение — основано на принципе, предполагающем начало разработки с общего знаменателя, с минимальных технических требований и уровня опыта взаимодействия пользователя, предлагаемого сайтом. Посетители, заходящие на сайт через последние версии браузеров и устройств, будут обслуживаться прогрессивно расширяемой версией сайта со всеми новейшими функциями.
С другой стороны, пользователям старых браузеров и медленного интернет-соединения будет предлагаться графически усеченная, но все еще функциональная версия сайта.
Подобный подход при реализации кроссбраузерности предполагает начало разработки с простой версии, к которой затем добавляются более сложные элементы. Старые браузеры смогут отображать сайт с базовым уровнем опыта взаимодействия. А новые функции HTML / CSS / JavaScript будут доступны в браузерах, которые могут реально их использовать.
В противоположность этому, постепенное упрощение обеспечивает полнофункциональный уровень UX в современных браузерах. А затем постепенно уменьшает его сложность для старых браузеров за счет графики, но, не касаясь функционала. Идея заключается в том, чтобы начать разработку с новейших веб-стандартов, а затем попытаться минимизировать проблемы, связанные со старыми браузерами.
Какой подход выберете вы, зависит от личных предпочтений и условий проекта:
- Прогрессивное улучшение обеспечивает большую стабильность, так как вы можете постепенно добавлять новые функции для современных браузеров. Но оно требует более тщательного планирования;
- Некоторые разработчики утверждают, что нет смысла поддерживать устаревшие браузеры и должны использоваться новейшие технологии. Поддержка современных браузеров дает намного лучший опыт взаимодействия;
- Существует мнение, что прогрессивное улучшение мертво, так как множество JavaScript-приложений не работают надлежащим образом при этом подходе;
- Веб-доступность для общественных учреждений может быть определена в юридических требованиях конкретных территориальных образований, и это может повлечь необходимость применения особого подхода.
Учитывая появление таких инструментов для определения функций, как Modernizr , лично я склоняюсь к использованию постепенного упрощения и черного списка браузеров при разработке совместимых сайтов.
4. Тестирование, тестирование, тестирование…
Чтобы как можно скорее обнаружить потенциальные проблемы кроссбраузерности JavaScript , нужно в процессе разработки тестировать сайт в различных браузерах и разрешениях. Существуют различные программные эмуляторы, которые могут нам помочь:
- Browserstack — это коммерческий сервис, который предоставляет доступ к тестовой среде, в которой можно проверить свой проект более чем на 700 стационарных браузерах и мобильных устройствах с помощью виртуальной машины в облаке;
- Microsoft Virtual Machines — если вы работаете в Linux, у вас не будет доступа к Internet Explorer . Решение может заключаться в том, чтобы загрузить образы виртуальных машин для IE6 в IE11 , которые затем могут использоваться в сочетании с Oracle VM Virtualbox или Vagrant для локального тестирования;
- Различные разрешения экрана для конкретного браузера можно быстро протестировать с помощью онлайн-сервиса Screenfly . С использованием плагинов для браузеров, таких как Window Resizer для Google Chrome , или непосредственно в разделе инструментов для разработчиков Chrome и Firefox .
5. Normalize.css и CSS Autoprefixer
Обычно я начинаю новые проекты со сброса CSS с помощью Normalize.css , который обеспечивает лучшую кроссбраузерность при определении стилей HTML-элементов , используемых по умолчанию, вплоть до Internet Explorer 8 . Normalize.css сохраняет нужные стили элементов, нормализует их внешний вид и исправляет ряд ошибок и несоответствий в различных браузерах.
Кроме этого многие устаревшие браузеры не могут интерпретировать неизвестные элементы HTML и свойства CSS . Когда браузер встречает фрагмент HTML или CSS , который он не понимает, то игнорирует его и продолжает процесс отображения. Многие приложения используют вендорные префиксы, чтобы добавить новые, экспериментальные или нестандартные функции CSS до их реализации в спецификации:
// Webkit-браузеры, такие как Chrome и Safari -webkit- // Firefox -moz- // Internet Explorer -ms- // Opera -o-
Проблема заключается в том, что префиксы неудобны в использовании и с ними связано много ошибок. Поэтому я использую плагин CSS Autoprefixer в сочетании с Grunt .
Обычные правила CSS будут обработаны с помощью плагина и к ним будут добавлены префиксы на основе базы данных «Can I Use «. Рекомендуется задать в конфигурации версии браузеров, которые нужно поддерживать, например:
options: { browsers: ["last 2 versions", "ie >= 8", "Firefox >= 12", "iOS >= 7", "Android >= 4"] }
В качестве примера рассмотрим следующий класс CSS :
Example { background-image: linear-gradient(top left, #4676dd, #00345b); display: flex; transition: 1s all; }
С помощью CSS Autoprefixer он преобразуется в:
Example { background-image: -webkit-linear-gradient(top left, #4676dd, #00345b); background-image: -moz-linear-gradient(top left, #4676dd, #00345b); background-image: linear-gradient(top left, #4676dd, #00345b); display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; -webkit-transition: 1s all; -moz-transition: 1s all; transition: 1s all; }
6. Условные комментарии
Если нужно создать резервный CSS или включить кроссбраузерность JavaScript для ранних версий Internet Explorer , то можете использовать условные комментарии . Они поддерживаются в Internet Explorer 5-9 , они используют синтаксис комментариев HTML в сочетании с логическими значениями. В зависимости от логического значения (true или false ) код внутри тегов комментариев будет выводиться или скрываться в соответствующих версиях браузера:
CODE TO BE PERFORMED // если Internet Explorer // если НЕ Internet Explorer // если Internet Explorer 7 // если НЕ Internet Explorer 7 // если Internet Explorer 9 или НИЖЕ // если Internet Explorer 7 или ВЫШЕ // если Internet Explorer 6 ИЛИ 7 // если ВЫШЕ Internet Explorer 6 НО НИЖЕ 9
Код автоматически скрывается во всех браузерах, не поддерживающих условные комментарии. Наглядным примером того, как условные комментарии могут быть эффективно использованы на практике, является HTML5 Boilerplate , который добавляет специфические классы CSS для устаревших версий Internet Explorer :
7. Polyfills
Technical inconsistencies of outdated browsers for responsive web design can be corrected using polyfill. It is a piece of JavaScript code that “fills” a specific functional gap between an outdated browser and a function. There are a number of polyfills that can be used to provide browser support for HTML5 features.
Below are a few polyfills designed to address the cross-browser issues of the site, referred to in paragraph 3:
- respond.js - implements cSS3 media queries for Internet Explorer 6 - 8;
- html5shiv enables the use of HTML5 semantic elements in Internet Explorer 6-8;
- selectivzr - emulates CSS3 selectors and pseudo-classes in Internet Explorer 6 - 8. Full support requires either Mootools 1.3 or NWMatcher 1.2.3. Partial support is available with jQuery 1.3 / 1.4;
- REM-unit-polyfill - Determines whether the browser supports rem units and provides a fallback. Works with IE8 and below.
To use these polyfills, they must be added from the CDN or as a file in the correct format inside conditional comments in the section
(do not forget to include one of javaScript Needed for Selectivizr):
For each project, you need to evaluate whether these additional scripts are really needed, as they can lead to performance problems. Most polyfills are compact, but each additionally loaded script is an additional HTTP request. This may slow down page loading.
8. Defining functions using Modernizr
JavaScript Modernizr library will help you check the site’s cross-browser compatibility: whether a specific HTML5 or CSS3 function is supported in different browsers. If the function is not available, alternative CSS or JavaScript code may be loaded.
The idea is to directly determine the functionality of the browser, and not try to install a specific version of it. And on the basis of this, derive its functionality, which is a less efficient and reliable way.
It is worth noting that Modernizr does not add missing features to the browser. Therefore, you will need to provide code from fallback CSS or polyfill.
First you need to download a fully functional assembly. Later, when you are ready to develop, you can create custom assembly with specific features that you are testing. All you need to do is add the .no-js class to the site’s HTML tag and include the Modernizr script in the head section after any CSS file:
Modernizr demo
This is a Modernizr exercise.
The .no-js class is used to check if JavaScript is enabled in the user's browser. If enabled, Modernizr will replace .no-js with the .js class. Test function Modernizr analyzes whether a particular function is supported in the browser and generates a series of classes that are added to the HTML element. Google Chrome 47.0.2526.111, for example, will return the following object classes.
Modernizr is currently available as a global object that can be called in conjunction with the function name to check if it exists. It returns a boolean value ( true or false).
Let's look at two simple examples of CSS and JavaScript.
Cross-browser CSS CSS problem solving example: checking SVG support and providing PNG as a fallback
Currently, there is a trend towards an increasingly active use of SVG ( Scalable vector graphics), but this graphic is not supported in IE8 and below. If SVG is supported in a browser, Modernizr generates a CSS class.svg. If SVG is not available, the tool adds the .no-svg class to the HTML. Using the CSS below, SVG-enabled browsers will use the regular .logo class, while non-SVG browsers will use .no-svg rules:
Logo (background-image: url ("logo.svg"); width: 164px; height: 49px;) .no-svg .logo (background-image: url ("/logo.png"); width: 164px; height: 49px;)
JavaScript example: defining border-radius and adding appropriate CSS classes
Rounding the corners of the frame is not supported in IE8 and below. We can create various CSS classes that are used depending on the presence of the border-radius function:
// Class for the browser with the border-radius function .round-borders (border-radius: 5px;) // Class for the browser without the border-radius function .black-borders (border: 3px solid # 000000;)
Now you can use JavaScript to save the target identifier as a variable, and then add CSS classes through the condition:
var element \u003d document.getElementById ("TestID"); if (Modernizr.borderradius) (element.className \u003d "round-borders";) else (element.className \u003d "black-borders";)
Conclusion
When it comes to responsive web design in legacy browsers, there is no universal solution. It is important to analyze the audience of the resource in order to get an idea of \u200b\u200bthe real number of browser users. Then you need to thoroughly test the site to identify potential cross-browser problems.
Published: 06/07/2011
I will once again describe the hacks for the different browsers well-known and 100,500 times described earlier.
Here is the definition of a hack from Vlad Mergevich’s website htmlbook.ru: “A hack is a set of techniques aimed at setting the style of a certain element for one browser that would be different from the style for other browsers.”
First of all, I was interested in current working solutions, so I checked all the examples in the most recent, except IE, browser versions (Opera 11, Firefox 4, Chrome 13, Safari 5, IE 8).
Internet explorer
The most "different" to other browsers. Moreover, each version is "different" in its own way. However, we accept reality as it is. But the reality is that there are enough hacks for different versions of IE when layout to place them in a separate file and load only for this browser family. For this, in the section
HTML document, write a comment that can recognize Internet Explorer.
The following keywords can be used as a condition:
- IE - any version of Internet Explorer;
- IE 7 - Internet Explorer 7;
- IE 8 - Internet Explorer 8;
- IE 9 - Internet Explorer 9;
- lt - browser version number less than the specified;
- gt - version number is greater than specified;
- lte - version number is less than or equal to the specified;
- gte - browser version number is greater than or equal to the specified.
Perhaps I’ll separately mention a hack for IE 7: an asterisk in front of the selector name. For example:
#example (
color: green;
* color: red;
}
Chrome and Safari
Hack for browsers based on the webkit engine - Chrome and Safari:
@media screen and (-webkit-min-device-pixel-ratio: 0) (
#example (
color: red;
}
}
Firefox
@ -moz-document url-prefix () (
#example (
color: red;
}
}
Opera
There are no universal hacks for Opera! Yes, of course, you can find hacks for the Opera on the network, but, alas, this information is a bit outdated. There was once a hack, but the whole thing came out:
@media all and (min-width: 0px) (
}
Hmm, if there are hacks for all browsers, but not for Opera, the logical conclusion is: first you need to make up for Opera, and then polish the layout for other browsers. How do you look at it?
UPD 08/09/11: The latest reports from the fronts: on Habré there was a hack for the Opera. Here is one:
@media all and (-webkit-min-device-pixel-ratio: 10000),
not all and (-webkit-min-device-pixel-ratio: 0) (
#example (color: red;)
}
However, I highly recommend not using it. I will give as an argument the comment of Vadim Makeev (aka Pepelsbey): "These hacks are based on incomplete or erroneous support for Media Queries and can break with any minor browser update that will fix or supplement support. Do not shoot yourself in the foot, do not use potentially dangerous hacks.". Which, in fact, happened with the first hack for the Opera, mentioned in this article.
Based on this, we still believe that the best hack for the Opera browser is a competent, valid layout.