Skip to content

surajhume/html5checklist

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 

Repository files navigation

Чеклист верстки

Для того чтобы отдавать вёрстку клиенту, достаточно соблюдения первых 5 пунктов. Для выдачи в продакшен — первых 6.

Подробности по каждому пункту: http://habrahabr.ru/post/114256/

  1. Соответствие макету
  2. Кроссбраузерность, кодировка и DOCTYPE
  3. Валидность (включая CSSLint и JSHint), доступность (ARIA, WCAG), микроформаты (microformats 1 & 2, microdata)
  4. Независимость блоков в CSS: минимизация каскада, использование техник БЭМ
  5. Сайт должен нормально смотреться во всех стандартных разрешениях от 320 и выше, не иметь горизонтального скролла и вписываться в экран мобильных устройств
  6. Корректная работа при вбивании реального текста, надёжность вёрстки
  7. CSS должен быть написан с использованием препроцессоров (LESS/Sass/Stylus). Желательно использование систем сборки (Grunt/Gulp) и построцессоров (PostCSS/Autoprefixer).
  8. Проверка и оптимизация скорости загрузки: https://github.com/ihorzenich/WebPerformanceChecklist
  9. Поддержка Retina
  10. Наличие Win/Mac/Linux-аналогов шрифтов
  11. Доступность при выключенных(загружающихся) картинках
  12. HTML5 формы, линковка, валидация
  13. Семантичность. Отсутствие глупостей в html и css, единообразие, аккуратность (смотри "Плохо/хорошо")
  14. Правильная структура заголовков (H1,H2,… и т.д. и TITLE)
  15. Работоспособность при выключенном (незагруженном) JavaScript
  16. Работоспособность при выключенном Flash
  17. Отсутствие багов при увеличенном шрифте

13. "Плохо"/"Хорошо"

Важно понимать что семантика — может быть не только в используемых элементах, но и в именах классов. И БЭМ-иерархия классов — это новый уровень семантики.

Плохо:

  • Самое страшное, к счастью уже редкое — float: left для всех блоков. Безумный верстальщик эмулирует привычные ячейки таблиц, расставляя блоки как кирпичи друг за другом. Вон из профеcсии!
    Проверяется в extension для браузеров Web Developer → Outline → Outline Floated Elements, если всё в красных блоках, вёрстку нужно выкидывать на помойку.
    Так же, такая верстка получается при создании сайтов на Adobe Muse.
    Примеры: один - два - три
  • Отступы между блоками на сайте должны быть за счёт margin у блоков, а не выпирающих наружу margin у содержимого блоков.
  • Плохо — отсутствие тайтлов.
  • Плохо — отсутствие alt у картинок.
  • Плохо — хаки для браузеров внутри main.css (как без фильтров, так и с ними). Без фильтров — это когда когда просто пишем {zoom: 1;} — это оч. плохо, т.к. будет применяться ко всем IE, а не только к тому, в котором проблема. С фильтрами — когда пишут (* html, *+html и т.д.) — плохо, потому что это засоряет код, делает его менее читабельным, а какие-то хаки могут быть и вообще невалидными и нарушать прогон CSSLint. Conditional Comments — тоже плохо, хотя раньше считалось хорошей техникой, плохо т.к. это увеличение кол-ва css-файлов и главное — это разнесение кода в разные места. Сейчас рекомендуется использовать специальные классы типа html.ie7, html.ie8,… (из HTML5 Boilerplate), Modernizer-детектирование фич (классы вида html.js.flexbox.canvas.no-touch…) и JS-детектирование браузера и платфорым (например CSS Browser Selector генерирующий классы вида html.webkit.chrome.chrome25.win.win8…)
  • Плохо — не проверять tabindex в формах.
  • Плохо — писать стили не думая о логике размещения элементов. Например, если элемент всегда находится сверху, у него должен быть большой z-index, нельзя надеяться на то что сейчас всё нормально смотрится — стили должны быть железобетонными. Если элемент всегда должен находится на каком-то месте, в независимости от окружающих его элементов — это position: absolute; а не float и т.д. Блоки независящие друг от друга не должны быть внутри одного блока (например телефон компании и поиск по сайту). Блоки независящие по расположению друг от друга должны быть position absolute, а не float’ится.
  • Очень плохо — презентационные классы (right, red).
  • Нежелательно когда вёрстка содержит пустые блоки для презентационных целей, для этого существуют псевдоэлементы
  • Плохо когда нет базовых стилей у стандартных элементов. Т.е. просто h1,h2,ul,table,etc без классов должны смотреться красиво и органично. Проще говоря — используйте Normalize, a не Reset CSS.
  • Плохо когда нет постепенного уточнения стилей для текста, когда стиль выписывается для каждого элемента отдельно, а за его пределами — внешний вид может быть кардинально другой. Речь о ситуации когда например текст, написанный без абзацев, имеет вообще не тот стиль что у всех элементов в блоке. Надо вести стили снизу вверх, постепенно уточняя их. Тут важно не путать стили для текста и стили для блоков. Для текста — каскад это добро, для блоков сайта — нужно использовать БЭМ.
  • Ещё хуже — чересчур детализированные глобальные стили. Например a {font: italic 10px Tahoma;} /* Ненависть! Ненависть! НЕНАВИСТЬ!!11 */ Потом приходится переопределять стиль ссылок для каждого блока.
  • Размеры и позиционирование элемента должны указываться в одних единицах измерения. Т.е. высота/ширина блока в px и margin/padding в em — это странно и скорей всего ошибка. Line-height — лучше задавать коэффициентом (1/1.2/1.4... т.е. без указания единицы измерения — это цифра на которую умножается font-size и получится межстрочный интервал). Если задали font-size/height в em — значит задаём и margin/padding тоже в em. Классический пример: список dl-dt-dd, где dt и dd ставятся друг на против друга с помощью подтягивания dd отрицательным margin вверх. Или — выделили padding’ом место под position: absolute какого-то текстового блока. У текстовых элементов (абзацей, ячеек таблиц) задаём padding и height в em (чтоб корректно увеличивать размер шрифта) .
  • Плохо(недопустимо!) вешать стили на селекторы вложенных стандартных тэгов, без классов. Т.е. допустим пишем что-то типа h2 a span {какая-то крепкая штука, типа картинки с графикой, что закрывает текст в заголовке}, а потом клиент в визиге внезапно вбивает такое сочетание! И получаем невероятный баг. На просто одиночные теги для вывода текста из БД — можно, но используя блок .b-text (смотри BEM CSS).
  • Плохо — напрямую задавать визуальное отображение элементов через js: $('.element').css(color,"#f00"). Это должно делаться через установку/смену классов.

Хорошо:

  • БЭМ! Важно понимать что это методология, а не инструменты. Для обычных сайтов достаточно вёрстки по BEM CSS, без использования библиотеки блоков и bem-tools. Я долго считал что «BEM — это классная идея, но это чересчур, так категорично не надо, надо чуть по-другому, под себя...», так вот — это неверно! Нужно обязательно уходить от каскада, а БЭМ — это один из отличных вариантов решения.
  • Хорошо — структурировать код в блоки описывающие логику документа. Т.е. создавать div даже там, где он для презентационных целей не нужен. И наоборот — стараться не ставить лишний div там, где структура этого не требует, а это нужно лишь для визуальных эффектов.
  • HTML5 Boilerplate — замечательный стартовый шаблон от «отцов». Используйте и присоединяйтесь к разработке, добавляйте свои велосипеды туда! Раньше у нас был свой самописный framework-стартовый html, теперь используем Boilerplate как основу, а в него уже добавляем старые наработки.
  • Используйте наработанные решения, чужие модули, jQuery-плагины, не изобретайте велосипедов, а если изобретаете — поддерживайте их, ведите библиотеку кода (после каждого нового проекта добавляйте туда код, обновляйте старый).
  • Для текстовых блоков, что редактируются в админке, должна обеспечиваться атомарность текстовых стилей. Т.е. есть у нас страничка с каким-то текстовым блоком, примерно такой структуры: ```css .content-text h1 .content-text .entry .content-text .entry .somenamedblock ``` То .somenamedblock должен получать текстовые стили непосредственно — .somenamedblock {font: …; color: …;}, т.к. иначе в визиге админки мы не сможем их застайлить.
  • одинаковый html-код для блоков на морде и внутряках, с идентичным контентом, но разным визуальным представлением данных. Реализуется через модификаторы блоков и элементов, но не через модификацию от родителя (каскад от body.pagename например!)

Важные мелочи

  • Лого на внутряках должно вести на титулку. На титулке logo = h1, на внутряках H1=заголовок контента, а Logo=div
  • У каждой страницы должен быть свой уникальный TITLE формата About Us — %CompanyName%
  • Все страницы должны быть слинкованы и проверены на наличие битых ссылок.
  • Все ссылки должны как-то реагировать на :hover, :active и :focus — показыванием/убиранием подчёркивания, сменой цвета, чем угодно. У всех ссылок, кроме пунктов меню, должна быть реакция на :visited
  • Проверять что все интерактивные элементы страницы что должны работать — работают.
  • «Контент в начале страницы» — содержимое страницы должно идти в начале кода, до всяких сайдбаров и прочего.
  • Все созданные странички изначально должны быть порезаны на шаблоны, чтоб программеру было легче их интегрировать.
  • Копирайт должен быть написан правильно.
  • Должны быть favicon.ico (желательно с включенными внутрь неё 32×32, 48×48 и 64×64 вариациями) и apple-touch-icon
  • В вёрстке не должны оставаться закомментированные «на всякий случай» куски кода, лишние неиспользуемые файлы, старые версии файлов и т.п. Все бекапы можно вытянуть из системы контроля версий (например Git или SVN), а на живом проекте «мусор» потом мешает разобраться как что работает.
  • Размеры для блоков, чьи размеры зависят от содержащегося в них текста, нужно задавать в em, а не px.
  • Если url ссылки неизвестен, то он должен быть равен её анкору, написанному латиницей с заменой пробелов/спецсимволов на тире.
  • Skype-плагин не должен ломать вёрстку
  • Ресайз textarea не должен ломать вёрстку
  • При проверке frontend в целом — 404-страница должна отдаваться с кодом 404 а не 200.
  • Нужно подстраховываться фиксируя в css размеры картинок, выводящихся программно.
  • Проверка орфографии Word’ом или Орфографом, желательно — оттипографить контент.
  • Ссылки на чужие сайты должны быть с target="_blank", желательно выделять их иконкой «внешняя ссылка».
  • Разумеется картинки должны быть в отдельной папке, css — в отдельной и js — в отдельной. Графика, не являющаяся частью дизайна (всякие илююстрации, фото в новостях и т.д.) — нужно положить в отдельную папку, например userfiles.
  • Изображения должны масштабироваться в зависимости от размера окна (max-width:100%; height:auto;)

[README IN ENGLISH]

Layout checklist In order to give the layout to the client, it is enough to comply with the first 5 points. For distribution to production - the first 6.

Details for each item: http://habrahabr.ru/post/114256/

Compliance with the layout Cross-browser, encoding and DOCTYPE Validity (including CSSLint and JSHint), accessibility (ARIA, WCAG), microformats (microformats 1 & 2, microdata) Block independence in CSS: minimizing the cascade, using BEM techniques The site should look normal in all standard resolutions from 320 and higher, not have horizontal scrolling and fit into the screen of mobile devices Correct work when driving in real text, layout reliability CSS should be written using preprocessors (LESS / Sass / Stylus). It is desirable to use build systems (Grunt / Gulp) and builders (PostCSS / Autoprefixer). Checking and optimizing download speed: https://github.com/ihorzenich/WebPerformanceChecklist Retina support Availability of Win / Mac / Linux-like fonts Availability with disabled (loading) pictures HTML5 forms, linking, validation Semantics. No nonsense in html and css, uniformity, neatness (see "Good / bad") Correct heading structure (H1, H2, ... etc. and TITLE) Performance with disabled (unloaded) JavaScript Performance when Flash is off No bugs with large font 13. "Bad" / "Good" It is important to understand that semantics can be not only in the elements used, but also in the class names. And the BEM class hierarchy is a new level of semantics. Bad:

The worst thing, fortunately already rare, is float: leftfor all blocks. Crazy layout designer emulates familiar table cells, placing blocks like bricks one after another. Get out of the profession! It is checked in the browser extension Web Developer → Outline → Outline Floated Elements, if everything is in red blocks, the layout needs to be thrown into the trash. Also, such a layout is obtained when creating sites in Adobe Muse . Examples : one - two - three Indents between blocks on the site should be due to the margin of the blocks, and not protruding margins of the content of the blocks. Bad - the lack of titles. Bad - the lack of alt in images. Bad - hacks for browsers inside main.css (both without filters and with them). Without filters - this is when when we just write {zoom: 1;}- it's very good. bad because will apply to all IEs, not just the one with the problem. With filters - when they write (* html, *+html и т.д.)- it is bad, because it clogs the code, makes it less readable, and some hacks may be generally invalid and break the CSSLint run. Conditional Comments is also bad, although it was previously considered a good technique, it is bad because this is an increase in the number of css files, and the main thing is the distribution of the code to different places. Now it is recommended to use special classes like html.ie7, html.ie8,…(from HTML5 Boilerplate), Modernizer-detection of features (view classes html.js.flexbox.canvas.no-touch…) and JS-detection of browser and platform (for example, CSS Browser Selector generating view classes html.webkit.chrome.chrome25.win.win8…) Bad - not checking tabindex on forms. It's bad to write styles without thinking about the logic of the elements' placement. For example, if an element is always on top, it should have a large z-index, you can't hope that everything looks fine now - the styles should be reinforced concrete. If an element should always be in some place, regardless of the surrounding elements, this is position: absolute; not float, etc. Blocks that are independent of each other should not be inside the same block (for example, company phone number and site search). Blocks that are independent of each other should be position absolute, not floated. Very bad - presentation classes (right, red). It is undesirable when the layout contains empty blocks for presentation purposes, for this there are pseudo-elements It's bad when standard elements do not have basic styles. Those. just h1, h2, ul, table, etc without classes should look nice and organic. Simply put - use Normalize, not Reset CSS. It's bad when there is no gradual refinement of styles for the text, when the style is written for each element separately, and outside of it - the appearance can be radically different. We are talking about a situation when, for example, text written without paragraphs has a completely different style than all the elements in the block. It is necessary to lead the styles from the bottom up, gradually refining them. It is important not to confuse text styles and block styles here. For text - a cascade is good, for site blocks - you need to use BEM. Worse, overly detailed global styles. For example a {font: italic 10px Tahoma;}/ * Hate! Hatred! HATE !! 11 * / Then you have to override the link style for each block. The dimensions and positioning of the element must be specified in the same units of measurement. Those. block height / width in px and margin / padding in em is strange and most likely a bug. Line-height - it is better to set it by a factor (1 / 1.2 / 1.4 ... i.e. without specifying the unit of measurement - this is the number by which the font-size is multiplied and the line spacing will be obtained). If we set the font-size / height in em, then we set the margin / padding in em too. Classic example: list dl-dt-dd, where dt and dd are stacked against each other by pulling dd up with a negative margin. Or - we allocated a padding space under the position: absolute of some text block. For text elements (paragraph, table cells), set padding and height in em (to correctly increase the font size). It is bad (unacceptable!) To hang styles on the selectors of nested standard tags, without classes. Those. let's say we write something like h2 a span {какая-то крепкая штука, типа картинки с графикой, что закрывает текст в заголовке}, and then the client in the vizig suddenly drives in such a combination! And we get an incredible bug. On just single tags to display text from the database - it is possible, but using the .b-text block (see BEM CSS). Bad - directly set the visual display elements through js: $('.element').css(color,"#f00"). This should be done through setting / changing classes. Okay:

BEM ! It is important to understand that this is a methodology, not tools. For ordinary sites, layout using BEM CSS is enough , without using a block library and bem-tools. For a long time I thought that “BEM is a great idea, but this is too much, so categorically it is not necessary, it is necessary a little differently, for yourself ...” , and so - this is not true! It is imperative to leave the cascade, and BEM is one of the great solutions. It's good to structure the code into blocks that describe the logic of the document. Those. create a div even where it is not needed for presentation purposes. And vice versa - try not to put an extra div where the structure does not require it, and this is necessary only for visual effects. HTML5 Boilerplate is a great starter template from the fathers. Use and join development, add your bikes there! Previously, we had our own self-written framework-starting html, now we use Boilerplate as a basis, and we are already adding old developments to it. Use well-established solutions, other people's modules, jQuery plugins, don't reinvent the wheel, but if you do, support them, maintain the code library (add code there after each new project, update the old one). For text blocks that are edited in the admin panel, the atomicity of text styles must be ensured. Those. we have a page with some kind of text block, something like this: '' css .content-text h1 .content-text .entry .content-text .entry .somenamedblock Then .somenamedblock must receive text styles directly - .somenamedblock {font: …; color: …;}since otherwise, we will not be able to freeze them in the admin panel visig. the same html-code for the blocks on the face and inside, with identical content, but different visual presentation of data. It is implemented through block and element modifiers, but not through the modification from the parent (cascade from body.pagename for example!) Important little things The logo on the inner liners should lead to the title. On the title, logo = h1, on the inner liners, H1 = content title, and Logo = div Each page must have its own unique TITLE format About Us — %CompanyName% All pages must be linked and checked for broken links . All links should somehow react to: hover,: active and: focus - by showing / removing the underline, changing the color, whatever. All links except menu items must have a reaction to: visited Check that all interactive elements of the page that should work - work. "Content at the beginning of the page" - the content of the page should go at the beginning of the code, before any sidebars and other things. All created pages should initially be cut into templates to make it easier for the programmer to integrate them. The copyright must be correct . There should be a favicon.ico (preferably with 32 × 32, 48 × 48 and 64 × 64 variations included inside it) and an apple-touch-icon The layout should not contain pieces of code commented out "just in case", unnecessary unused files, old versions of files, etc. All backups can be pulled from the version control system (for example, Git or SVN), and on a live project, "garbage" then prevents you from figuring out how what works. Sizes for boxes whose sizes depend on the text they contain should be specified in em, not px. If the url of the link is unknown, then it must be equal to its anchor, written in Latin, with spaces / special characters replaced with dashes. Skype plugin shouldn't break the layout Resize textarea should not break the layout When checking the frontend as a whole, a 404 page should be returned with a 404 code, not 200. You need to be on the safe side by fixing the sizes of images displayed programmatically in css. Check spelling by Word or Spelling , preferably - to print the content. Links to other people's sites should be with target="_blank", it is desirable to highlight them with an "external link" icon. Of course, pictures should be in a separate folder, css - in a separate one and js - in a separate one. Graphics that are not part of the design (all sorts of illustrations, photos in the news, etc.) - must be placed in a separate folder, for example userfiles. Images should be scaled based on window size (max-width:100%; height:auto;)

About

HTML/CSS markup checklist

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • CSS 100.0%