- Saved searches
- Use saved searches to filter your results more quickly
- License
- necolas/normalize.css
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- О normalize.css
- Обзор
- Нормализовать или сбрасывать?
- Normalize.css сохраняет полезные настройки по умолчанию
- Normalize.css исправляет популярные ошибки
- Normalize.css не мешает вашим инструментам отладки
- Normalize.css модульный
- Normalize.css имеет подробную документацию
- Как использовать normalize.css
- Заключение
- Вся информация о стилях по умолчанию
- About normalize.css
- Overview
- Normalize vs Reset
- Normalize.css preserves useful defaults
- Normalize.css corrects common bugs
- Normalize.css doesn’t clutter your debugging tools
- Normalize.css is modular
- Normalize.css has extensive documentation
- How to use normalize.css
- Closing comments
- Related reading
- Translations
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A modern alternative to CSS resets
License
necolas/normalize.css
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A modern alternative to CSS resets
npm install --save normalize.css
- Preserves useful defaults, unlike many CSS resets.
- Normalizes styles for a wide range of elements.
- Corrects bugs and common browser inconsistencies.
- Improves usability with subtle modifications.
- Explains what code does using detailed comments.
- Chrome
- Edge
- Firefox ESR+
- Internet Explorer 10+
- Safari 8+
- Opera
Extended details and known issues
Additional detail and explanation of the esoteric parts of normalize.css.
The font-family: monospace, monospace hack fixes the inheritance and scaling of font-size for preformatted text. The duplication of monospace is intentional. Source.
Normally, using sub or sup affects the line-box height of text in all browsers. Source.
By default, Chrome on OS X and Safari on OS X allow very limited styling of select , unless a border property is set. The default font weight on optgroup elements cannot safely be changed in Chrome on OSX and Safari on OS X.
It is recommended that you do not style checkbox and radio inputs as Firefox’s implementation does not respect box-sizing, padding, or width.
Certain font size values applied to number inputs cause the cursor style of the decrement button to change from default to text .
The search input is not fully stylable by default. In Chrome and Safari on OSX/iOS you can’t control font , padding , border , or background . In Chrome and Safari on Windows you can’t control border properly. It will apply border-width but will only show a border color (which cannot be controlled) for the outer 1px of that border. Applying -webkit-appearance: textfield addresses these issues without removing the benefits of search inputs (e.g. showing past searches).
Please read the contribution guidelines in order to make the contribution process easy and effective for everyone involved.
О normalize.css
Это перевод статьи Николаса Галахера — «About normalize.css».
Это перевод статьи Николаса Галахера — «About normalize.css»
Normalize.css — это небольшой CSS-файл, который обеспечивает для HTML-элементов лучшую кроссбраузерность в стилях по умолчанию. Это современная, готовая к HTML5 альтернатива традиционному reset.css.
В настоящее время normalize.css используется в Twitter Bootstrap, HTML5 Boilerplate, GOV.UK, Rdio, CSS Tricks и во многих других фреймворках, инструментах и сайтах.
Обзор
Normalize.css является альтернативой CSS Reset. Проект является продуктом сотен часов глубокого исследования различий между изначальными стилями браузера. Это исследование провели Николас Галахер, @necolas и Джонатан Нил, @jon_neal.
- сохранять полезные настройки браузера, а не стирать их;
- нормализовать стили для широкого круга HTML-элементов;
- корректировать ошибки и основные несоответствия браузера;
- совершенствовать юзабилити незаметными улучшениями;
- объяснять код, используя комментарии и детальную документацию.
Он поддерживает широкий диапазон браузеров (в том числе мобильных) и включает в себя CSS, который нормализует HTML5-элементы, типографику, списки, встраиваемый контент, формы и таблицы.
Несмотря на то, что проект основан на принципе нормализации, он использует стандартные настройки там, где они предпочтительны.
Нормализовать или сбрасывать?
Стоит понимать более подробно, в чём отличие normalize.css от традиционного reset.css.
Normalize.css сохраняет полезные настройки по умолчанию
Reset.css накладывает однородный визуальный стиль, выравнивая стили по умолчанию почти для всех элементов. В отличие от этого, normalize.css сохраняет многие полезные стили браузеров по умолчанию. Это значит, что не требуется повторно объявлять стили для всех стандартных элементов типографики.
Когда элемент имеет различные стили по умолчанию в разных браузерах, normalize.css там, где это возможно, стремится сделать эти стили совместимыми и соответствующими современными стандартам.
Normalize.css исправляет популярные ошибки
Он исправляет основные баги на мобильных и десктопных устройствах, которые не затрагивает reset.css. Это включает в себя параметры отображения элементов HTML5, исправление font-size для предварительно отформатированного текста, отображение SVG в IE9, и многие другие баги, связанные с отображаемым в разных браузерах и операционных системах.
Например, вот как normalize.css делает HTML5-элемент формы с типом search кроссбраузерным и стилизованным.
/** * 1. Переопределяет свойство `appearance`, заменяет `searchfield` в Safari и Chrome. * 2. Переопределяет свойство `box-sizing`, заменяет `border-box` в Safari и Chrome. */ input[type="search"] < -webkit-appearance: textfield; /* 1 */ box-sizing: content-box; /* 2 */ >/** * Убирает внутренний отступ и кнопку очистки строки поиска в Safari и Chrome в OS X */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration
Reset.css часто не приводит браузеры к тому уровню, где отправной точкой считается то, как элемент отрисовывается. Это особенно верно в отношении форм — именно здесь normalize.css может существенно помочь.
Normalize.css не мешает вашим инструментам отладки
Обычно при использовании reset.css раздражает огромная цепочка наследования свойств, которая отображается в инструментах разработчика.
Такая проблема не возникает с normalize.css из-за целенаправленных стилей и умеренного использования множественных селекторов в наборе правил.
Normalize.css модульный
Проект разбит на относительно независимые участки, что позволяет увидеть, каким именно элементам нужны конкретные стили. Кроме того, это даёт вам возможность удалить блоки свойств (например, нормализацию форм), если известно, что они никогда не понадобятся на сайте.
Normalize.css имеет подробную документацию
Код normalize.css основан на детальном кроссбраузерном методичном тестировании. Подробно документированный файл вы можете найти на GitHub. Это значит, что вы можете узнать, что делает каждая строка кода, зачем она добавлена, какие различия существуют между браузерами. Также вы легко можете провести собственные тесты.
Цель проекта — показать людям, как по умолчанию браузеры отображают элементы, и помочь им упростить процесс внедрения улучшений.
Как использовать normalize.css
Сперва установите или скачайте normalize.css с GitHub. Есть два способа как можно его использовать.
Первый способ: используйте normalize.css как отправную точку CSS для вашего собственного проекта, изменяя значения согласно требованиям дизайна.
Второй способ: используйте normalize.css нетронутым и, основываясь на нём, переопределяйте стили в своём CSS при необходимости.
Заключение
Normalize.css значительно отличается от reset.css. Стоит попробовать его, чтобы увидеть, соответствует ли он вашему подходу и предпочтениям в разработке.
Проект развивается в открытом доступе на GitHub. Любой желающий может сообщить о проблемах и предложить исправления. Полная история проекта доступна всем для просмотра, а в коммитах и тикетах находятся контекст и причины всех изменений.
Вся информация о стилях по умолчанию
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
About normalize.css
Normalize.css is currently used in some form by Twitter Bootstrap, HTML5 Boilerplate, GOV.UK, Rdio, CSS Tricks, and many other frameworks, toolkits, and sites.
Overview
Normalize.css is an alternative to CSS resets. The project is the product of 100’s of hours of extensive research by @necolas and @jon_neal on the differences between default browser styles.
The aims of normalize.css are as follows:
- Preserve useful browser defaults rather than erasing them.
- Normalize styles for a wide range of HTML elements.
- Correct bugs and common browser inconsistencies.
- Improve usability with subtle improvements.
- Explain the code using comments and detailed documentation.
It supports a wide range of browsers (including mobile browsers) and includes CSS that normalizes HTML5 elements, typography, lists, embedded content, forms, and tables.
Despite the project being based on the principle of normalization, it uses pragmatic defaults where they are preferable.
Normalize vs Reset
It’s worth understanding in greater detail how normalize.css differs from traditional CSS resets.
Normalize.css preserves useful defaults
Resets impose a homogenous visual style by flattening the default styles for almost all elements. In contrast, normalize.css retains many useful default browser styles. This means that you don’t have to redeclare styles for all the common typographic elements.
When an element has different default styles in different browsers, normalize.css aims to make those styles consistent and in line with modern standards when possible.
Normalize.css corrects common bugs
It fixes common desktop and mobile browser bugs that are out of scope for resets. This includes display settings for HTML5 elements, correcting font-size for preformatted text, SVG overflow in IE9, and many form-related bugs across browsers and operating systems.
For example, this is how normalize.css makes the new HTML5 search input type cross-browser consistent and stylable:
/**
* 1. Addresses appearance set to searchfield in S5, Chrome
* 2. Addresses box-sizing set to border-box in S5, Chrome (include -moz to future-proof)
*/
input[type="search"]
-webkit-appearance: textfield; /* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box; /* 2 */
box-sizing: content-box;
>
/**
* Removes inner padding and search cancel button in S5, Chrome on OS X
*/
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button
-webkit-appearance: none;
>
Resets often fail to bring browsers to a level starting point with regards to how an element is rendered. This is particularly true of forms – an area where normalize.css can provide some significant assistance.
Normalize.css doesn’t clutter your debugging tools
A common irritation when using resets is the large inheritance chain that is displayed in browser CSS debugging tools.
This is not such an issue with normalize.css because of the targeted styles and the conservative use of multiple selectors in rulesets.
Normalize.css is modular
The project is broken down into relatively independent sections, making it easy for you to see exactly which elements need specific styles. Furthermore, it gives you the potential to remove sections (e.g., the form normalizations) if you know they will never be needed by your website.
Normalize.css has extensive documentation
The normalize.css code is based on detailed cross-browser research and methodical testing. The file is heavily documented inline and further expanded upon in the GitHub Wiki. This means that you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests.
The project aims to help educate people on how browsers render elements by default, and make it easier for them to be involved in submitting improvements.
How to use normalize.css
First, install or download normalize.css from GitHub. There are then 2 main ways to make use of it.
Approach 1: use normalize.css as a starting point for your own project’s base CSS, customising the values to match the design’s requirements.
Approach 2: include normalize.css untouched and build upon it, overriding the defaults later in your CSS if necessary.
Closing comments
Normalize.css is significantly different in scope and execution to CSS resets. It’s worth trying it out to see if it fits with your development approach and preferences.
The project is developed in the open on GitHub. Anyone can report issues and submit patches. The full history of the project is available for anyone to see, and the context and reasoning for all changes can be found in the commit messages and the issue threads.
Related reading
Translations
Nicolas lives and works in California. He’s on Threads and shares software using GitHub.