From e330c198ec41a59e07853861c82e61474b632bc3 Mon Sep 17 00:00:00 2001 From: Igor Baluev Date: Sun, 24 Jul 2022 11:49:01 +0300 Subject: [PATCH] Revert "Add Ukrainian translation" This reverts commit a34c8b6780bd04589b3ef354c53bcc3024bc7219. --- _config.yml | 2 +- _includes/header.html | 6 +- index.md | 457 ++++++++++++++++++++---------------------- 3 files changed, 217 insertions(+), 248 deletions(-) diff --git a/_config.yml b/_config.yml index 5f592c8..09321fe 100644 --- a/_config.yml +++ b/_config.yml @@ -1,5 +1,5 @@ name: Code Guide by @mdo -description: Стандарти для розробки послідовних, легких для редагування та підтримки HTML і CSS. +description: Standards for developing consistent, flexible, and sustainable HTML and CSS. url: https://codeguide.co permalink: pretty sass: diff --git a/_includes/header.html b/_includes/header.html index 35cf7f2..f8452f9 100644 --- a/_includes/header.html +++ b/_includes/header.html @@ -1,14 +1,14 @@
- Логотип Code Guide + Code Guide logo

- Посібник з написання коду + Code Guide

{{ site.description }}

- Автор @mdo · Переклад @igor-baluev · v{{ site.version }} · GitHub repo + Created by @mdo · v{{ site.version }} · GitHub repo

diff --git a/index.md b/index.md index 70ed32e..7388501 100644 --- a/index.md +++ b/index.md @@ -2,84 +2,82 @@ layout: default --- -

Зміст

+

Table of contents

-### [HTML](#html-section) +### [HTML](#html) -- [Синтаксис HTML](#html-syntax) +- [HTML syntax](#html-syntax) - [HTML5 doctype](#html5-doctype) -- [Атрибут мови](#language-attribute) -- [Режим сумісності з IE](#ie-compatibility-mode) -- [Кодування символів](#character-encoding) -- [Підключення CSS і JavaScript](#css-and-javascript-includes) -- [Практичність понад чистоту](#practicality-over-purity) -- [Порядок атрибутів](#attribute-order) -- [Булеві атрибути](#boolean-attributes) -- [Зменшуйте кількість розмітки](#reduce-markup) -- [Налаштування редактора](#editor-preferences) +- [Language attribute](#language-attribute) +- [IE compatibility mode](#ie-compatibility-mode) +- [Character encoding](#character-encoding) +- [CSS and JavaScript includes](#css-and-javascript-includes) +- [Practicality over purity](#practicality-over-purity) +- [Attribute order](#attribute-order) +- [Boolean attributes](#boolean-attributes) +- [Reduce markup](#reduce-markup) +- [Editor preferences](#editor-preferences)
-### [CSS](#css-section) - -- [Синтаксис](#css-syntax) -- [Порядок декларацій](#declaration-order) -- [Булеві властивості](#logical-properties) -- [Кольори](#colors-section) -- [Уникайте використання @import](#avoid-imports) -- [Розміщення @media](#media-query-placement) -- [Одиночні декларації](#single-declarations) -- [Скорочена нотація](#shorthand-notation) -- [Вкладеність в препроцесорах](#nesting-in-preprocessors) -- [Оператори в препроцесорах](#operators-in-preprocessors) -- [Коментарі](#comments) -- [Імена класів](#class-names) -- [Селектори](#selectors) -- [Дочірні та нащадкові селектори](#child-and-descendant-selectors) -- [Організація](#organization) +### [CSS](#css) + +- [CSS syntax](#css-syntax) +- [Declaration order](#declaration-order) +- [Colors](#colors) +- [Logical properties](#logical-properties) +- [Avoid @import`s](#avoid-imports) +- [Media query placement](#media-query-placement) +- [Single declarations](#single-declarations) +- [Shorthand notation](#shorthand-notation) +- [Nesting in preprocessors](#nesting-in-preprocessors) +- [Operators in preprocessors](#operators-in-preprocessors) +- [Comments](#comments) +- [Class names](#class-names) +- [Selectors](#selectors) +- [Child and descendant selectors](#child-and-descendant-selectors) +- [Organization](#organization)
-## Золоте правило +## Golden rule -Завжди дотримуйтеся цих чи власних узгоджених правил написання коду. Якщо знайшли помилку, велику чи маленьку, дайте знати. Для доповнень або внесків до цього посібника з коду, будь ласка, [відкрийте issue на GitHub](https://github.com/mdo/code-guide/issues/new). +Enforce these, or your own, agreed upon guidelines at all times. Small or large, call out what's incorrect. For additions or contributions to this Code Guide, please [open an issue on GitHub](https://github.com/mdo/code-guide/issues/new). - -> Кожен рядок коду має бути написаний однією особою, незалежно від кількості учасників. +> Every line of code should appear to be written by a single person, no matter the number of contributors. ## HTML -{: #html-section}
-### Синтаксис +### Syntax {: #html-syntax } -- Не використовуйте великі літери в тегах, включно у `doctype`. -- Використовуйте м'які відступи з двома пробілами — це єдиний спосіб гарантувати однакове відтворення коду в будь-якому середовищі. -- Вкладені елементи повинні мати один відступ (два пробіли). -- В атрибутах завжди використовуйте подвійні лапки і ніколи одинарні. -- Не використовуйте слеш ("/") у само-закриваючихся тегах. У [специфікації HTML5](https://html.spec.whatwg.org/multipage/syntax.html#syntax-start-tag) зазначено, що він не обов'язковий. -- Не уникайте опціональних закриваючих тегів (наприклад, `` або ``). +- Don't capitalize tags, including the doctype. +- Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment. +- Nested elements should be indented once (two spaces). +- Always use double quotes, never single quotes, on attributes. +- Don't include a trailing slash in self-closing elements—the [HTML5 spec](https://html.spec.whatwg.org/multipage/syntax.html#syntax-start-tag) says they're optional. +- Don’t omit optional closing tags (e.g. `` or ``).
```html - Заголовок сторінки + Page title Company -

Вітаю, світ!

+

Hello, world!

```
### HTML5 doctype -{: #html5-doctype } -Для більш передбачуваного відтворення сторінок в усіх браузерах застосовуйте [стандартний режим](https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode) за допомогою цього простого типу документа. Дотримуючись запропонованого синтаксису, пишіть у нижньому регістрі. +Enforce [standards mode](https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode) and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page. In keeping with the suggested syntax, keep it lowercase. +
```html @@ -95,29 +93,27 @@ layout: default ```
-### Атрибут мови -{: #language-attribute } +### Language attribute -Зі спеціфікації HTML5: +From the HTML5 spec: -> Авторам рекомендується вказувати атрибут `lang` у кореневому елементі `html`, вказуючи мову документа. Це допомагає інструментам синтезу мовлення визначати, яку вимову використовувати, інструментам перекладу визначати, які правила використовувати, і так далі. +> Authors are encouraged to specify a lang attribute on the root html element, giving the document's language. This aids speech synthesis tools to determine what pronunciations to use, translation tools to determine what rules to use, and so forth. -Дізнайтесь більше про атрибут `lang` [у спеціфікації](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element). Перейдіть на сайт IANA, щоб побачити [список кодів мов](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). +Read more about the `lang` attribute [in the spec](https://html.spec.whatwg.org/multipage/semantics.html#the-html-element). Head to the IANA for a [list of language codes](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry).
```html - + ```
-### Режим сумісності з IE -{: #ie-compatibility-mode } +### IE compatibility mode -Сьогодні немає потреби включати тег `` для сумісності документів в Internet Explorer, якщо вам не потрібна підтримка IE10 і старіших версій. Тег було відкинуто в IE11 і не використовується в Microsoft Edge (у поточній чи попередніх версіях). +There's no need to include the Internet Explorer document compatibility `` tag these days, unless you need support for IE10 and older. The tag was dropped in IE11 and isn't used in Microsoft Edge (legacy or otherwise). -Щоб отримати додаткові відомості, [прочитайте цю чудову статтю на сайті Stack Overflow](https://stackoverflow.com/questions/6771258/what-does-meta-http-equiv-x-ua-compatible-content-ie-edge-do). +For more information, [read this awesome Stack Overflow article](https://stackoverflow.com/questions/6771258/what-does-meta-http-equiv-x-ua-compatible-content-ie-edge-do).
```html @@ -126,12 +122,11 @@ layout: default ```
-### Кодування символів -{: #character-encoding} +### Character encoding -Забезпечте належне відтворення вмісту, оголосивши явне кодування символів. Це також дозволяє використовувати звичайні символи замість їхніх [HTML-сутностей](https://html.spec.whatwg.org/multipage/named-characters.html), наприклад `—` замість `&emdash;`, за умови, що їхнє кодування збігається з кодуванням документа. Для деяких зарезервованих символів XML, як-от амперсанд, нерозривні пробіли, менше/більше та лапки, вам все одно може знадобитися використовувати сутності символів HTML. +Ensure proper content rendering by declaring an explicit character encoding. This also allows you to use regular characters instead of their HTML entities, like `—` instead of `&emdash;`, provided their encoding matches that of the document. For some reserved XML characters—like ampersand, non-breaking spaces, less/greater than, and quotes—you may still need to use the HTML character entities. -UTF-8 є рекомендованим кодуванням. +UTF-8 is the recommended encoding.
```html @@ -139,28 +134,27 @@ layout: default -

Використовуйте довге тире "—", бо "emdash;" не потрібний в цьому кодуванні.

+

Use an em dash like so—no HTML entity required.

```
-### Підключення CSS і JavaScript -{: #css-and-javascript-includes} +### CSS and JavaScript includes -Відповідно до специфікації HTML5, як правило, немає необхідності вказувати атрибут `type`, коли підключаються файли CSS і JavaScript, оскільки `text/css` і `text/javascript` є відповідними значеннями за замовчуванням. +Per HTML5 spec, typically there is no need to specify a `type` when including CSS and JavaScript files as `text/css` and `text/javascript` are their respective defaults. -**Посилання на специфікації HTML5:** +#### HTML5 spec links -- [Використання елемента `link`](https://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-link-element) -- [Використання елемента `style`](https://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-style-element) -- [Використання елемента `script`](https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#the-script-element) +- [Using link](https://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-link-element) +- [Using style](https://www.w3.org/TR/2011/WD-html5-20110525/semantics.html#the-style-element) +- [Using script](https://www.w3.org/TR/2011/WD-html5-20110525/scripting-1.html#the-script-element)
```html - + - + @@ -170,26 +164,23 @@ layout: default ```
-### Практичність понад чистоту -{: #practicality-over-purity} +### Practicality over purity -Прагніть підтримувати стандарти та семантику HTML, але не на шкоду практичності. Використовуйте найменшу кількість розмітки з найменшою кількістю складнощів, коли це можливо. +Strive to maintain HTML standards and semantics, but not at the expense of practicality. Use the least amount of markup with the fewest intricacies whenever possible.
```html - + - +
...
```
+### Attribute order -### Порядок атрибутів -{: #attribute-order} - -Щоб легше було читати код, атрибути HTML краще ставити в такому порядку: +HTML attributes should come in this particular order for easier reading of code. - `class` - `id`, `name` @@ -200,12 +191,12 @@ layout: default - `tabindex` - `style` -Атрибути, які найчастіше використовуються для ідентифікації елементів, мають стояти на першому місці — `class`, `id`, `name` та `data-*`. Різноманітні атрибути, унікальні для певних елементів, йдуть на другому місці, за ними йдуть атрибути, пов’язані зі спеціальними можливостями та стилем. +Attributes that are most commonly used for identifying elements should come first—`class`, `id`, `name`, and `data` attributes. Miscellaneous attributes unique to specific elements come second, followed by accessibility and style related attributes.
```html - Посилання + Example link @@ -214,22 +205,19 @@ layout: default ```
-### Булеві атрибути -{: #boolean-attributes} - -Булевий атрибут — це атрибут, який не потребує наданого значення. XHTML вимагав надавати значення таким атрибутам, але HTML5 не має такої вимоги. +### Boolean attributes -Для подальшого читання зверніться до [секції WhatWG про булеві атрибути](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes) +A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement. -> Наявність булевого атрибута елемента представляє істине значення, а відсутність атрибута представляє хибне значення. +For further reading, consult the [WhatWG section on boolean attributes](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes) -Якщо вам необхідно включити значення атрибута, а **це не потрібно**, дотримуйтеся цієї вказівки WhatWG: +> The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. -> Якщо атрибут присутній, його значенням має бути порожня строка або [...] канонічне ім’я атрибута без пробілів на початку або в кінці. +If you must include the attribute's value, and **you don't need to**, follow this WhatWG guideline: -Тобто, наприклад, `checked="checked"` або `checked=""`. +> If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace. -Якщо підсумувати, **не додавайте значення** булевим атрибутам. +In short, **don't add a value**.
```html @@ -243,64 +231,60 @@ layout: default ```
-### Зменшуйте кількість розмітки -{: #reduce-markup} +### Reduce markup -По можливості уникайте зайвих батьківських елементів під час написання HTML. Це буде частіше вимагати додаткових ітерацій та рефакторингу при розробці сторінок, але HTML буде коротший. +Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML.
```html - + - + ```
-### Налаштування редактора -{: #editor-preferences} +### Editor preferences -Встановіть у своєму редакторі такі параметри, щоб уникнути поширених непослідовностей в коді та зайвих- відмінностей: +Set your editor to the following settings to avoid common code inconsistencies and dirty diffs: -- Використовуйте м’яку табуляцію, встановлену на два пробіли. -- Вирізайте кінцеві пробіли під час збереження. -- Встановлюйте кодування UTF-8. -- Додавайте новий рядок у кінці файлів. +- Use soft-tabs set to two spaces. +- Trim trailing white space on save. +- Set encoding to UTF-8. +- Add new line at end of files. -Спробуйте задокументувати та застосувати ці налаштування до файлу `.editorconfig` вашого проекту. Для прикладу дивіться [такий у Bootstrap](https://github.com/twbs/bootstrap/blob/main/.editorconfig). Дізнайтеся більше [про EditorConfig](https://editorconfig.org). +Consider documenting and applying these preferences to your project's `.editorconfig` file. For an example, see [the one in Bootstrap](https://github.com/twbs/bootstrap/blob/main/.editorconfig). Learn more [about EditorConfig](https://editorconfig.org).
## CSS -{: #css-section}
-### Синтаксис -{: #css-syntax} - -- Використовуйте м'яку табуляцію з двома пробілами — це єдиний спосіб гарантувати однакове відтворення коду в будь-якому середовищі. -- Групуючи селектори, зберігайте окремі селектори в одному рядку. -- Додайте один пробіл перед початковою дужкою блоків декларацій для розбірливості. -- Розмістіть закриваючі дужки блоків декларації на новому рядку. -- Додайте один пробіл після `:` для кожної декларації. -- Кожна декларація має відображатися в окремому рядку для більш точного звітування про помилки. -- Закінчуйте всі декларації крапкою з комою. Для останньої декларації це є необов’язковим, але без цього ваш код буде більш схильний до помилок. -- Значення властивостей, розділених комами, мають містити пробіл після кожної коми (наприклад, `box-shadow`). -- Використовуйте значення, розділені пробілами, для властивостей кольору (наприклад, колір: `color: rgb(0 0 0 / .5)`). [Для додаткової інформації див. розділ «Кольори»](#colors). -- Не додавайте до значень властивостей або параметрів кольору нуль на початку (наприклад, `.5` замість `0.5` і `-.5px` замість `-0.5px`). -- Усі шістнадцяткові значення пишіть у нижньому регістрі, наприклад, `#fff`. Малі літери набагато легше розрізнити під час сканування документа, оскільки вони мають більш унікальну форму. -- Використовуйте скорочені шістнадцяткові значення, якщо це можливо, наприклад, `#fff` замість `#ffffff`. -- Значення атрибутів у селекторах ставте в лапках, наприклад, `input[type="text"]`. [Вони необов’язкові лише в деяких випадках](https://mathiasbynens.be/notes/unquoted-attribute-values#css), і це гарна практика для підтримки послідовності стилю коду. -- Уникайте вказувати одиниці для нульових значень, наприклад, `margin: 0;` замість `margin: 0px;`. - - -Запитання щодо використаних тут термінів? Див. [розділ синтаксису статті CSS](https://uk.wikipedia.org/wiki/CSS#%D0%A1%D0%B8%D0%BD%D1%82%D0%B0%D0%BA%D1%81%D0%B8%D1%81) у Вікіпедії. +### Syntax +{: #css-syntax } + +- Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment. +- When grouping selectors, keep individual selectors to a single line. +- Include one space before the opening brace of declaration blocks for legibility. +- Place closing braces of declaration blocks on a new line. +- Include one space after `:` for each declaration. +- Each declaration should appear on its own line for more accurate error reporting. +- End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it. +- Comma-separated property values should include a space after each comma (e.g., `box-shadow`). +- Use space-separated values for color properties (e.g., `color: rgb(0 0 0 / .5)`). [See the Colors section for more information.](#colors) +- Don't prefix property values or color parameters with a leading zero (e.g., `.5` instead of `0.5` and `-.5px` instead of `-0.5px`). +- Lowercase all hex values, e.g., `#fff`. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes. +- Use shorthand hex values where available, e.g., `#fff` instead of `#ffffff`. +- Quote attribute values in selectors, e.g., `input[type="text"]`. [They’re only optional in some cases](https://mathiasbynens.be/notes/unquoted-attribute-values#css), and it’s a good practice for consistency. +- Avoid specifying units for zero values, e.g., `margin: 0;` instead of `margin: 0px;`. + +Questions on the terms used here? See the [syntax section of the Cascading Style Sheets article](https://en.wikipedia.org/wiki/Cascading_Style_Sheets#Syntax) on Wikipedia.
```scss -// Поганий CSS +// Bad CSS .selector, .selector-secondary, .selector[type=text] { padding:15px; margin:0px 0px 15px; @@ -308,7 +292,7 @@ layout: default box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF } -// Гарний CSS +// Good CSS .selector, .selector-secondary, .selector[type="text"] { @@ -320,29 +304,28 @@ layout: default ```
-### Порядок декларацій -{: #declaration-order} +### Declaration order -Декларації властивостей мають бути згруповані разом у такому порядку: +Property declarations should be grouped together in the following order: -1. Позиціонування -2. Блочна модель -3. Типографика -4. Візуалізація -5. Інше +1. Positioning +2. Box model +3. Typographic +4. Visual +5. Misc -Позиціонування стоїть на першому місці, оскільки воно може видалити елемент із звичайного потоку та замінити стилі, пов’язані з блочною моделлю. Блочна модель — `flex`, `float`, `grid`, чи `table` — відповідає розмірам, розміщенню та вирівнюванню компонента. Усе інше відбувається _всередині_ компонента або без впливу на попередні два розділи, тому вони йдуть останніми. +Positioning comes first because it can remove an element from the normal document flow and override box model related styles. The box model—whether it's flex, float, grid, or table—follows as it dictates a component's dimensions, placement, and alignment. Everything else takes place _inside_ the component or without impacting the previous two sections, and thus they come last. -Хоча `border` є частиною блочної моделі, більшість систем скидають [`box-sizing`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) на `border-box`, щоб `border-width` не впливала на загальні розміри. Це, у поєднанні зі збереженням `border` поблизу з `border-radius`, є причиною того, чому він знаходиться в розділі "Візуалізація". +While `border` is part of the box model, most systems globally reset the [`box-sizing`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing) to `border-box` so that `border-width` doesn't affect overall dimensions. This, combined with keeping `border` near `border-radius`, is why it's under the Visual section instead. -Міксини та функції препроцесора мають з’являтися там, де це найбільше підходить. Наприклад, міксин `border-top-radius()` буде замінювати властивості `border-radius`, а функція `responsive-font-size()` – замість `font-size`. +Preprocessor mixins and functions should appear wherever most appropriate. For example, a `border-top-radius()` mixin would go in place of `border-radius` properties, while a `responsive-font-size()` function would go in place of `font-size` properties. -Щоб отримати повний список властивостей і їх порядок, перегляньте [порядок властивостей для Stylelint](https://github.com/stormwarning/stylelint-config-recess-order), який використовується у [Bootstrap](https://getbootstrap.com). +For a complete list of properties and their order, please see the [property order for Stylelint](https://github.com/stormwarning/stylelint-config-recess-order) used by [Bootstrap](https://getbootstrap.com).
```scss .declaration-order { - // Позиціонування + // Positioning position: absolute; top: 0; right: 0; @@ -350,7 +333,7 @@ layout: default left: 0; z-index: 100; - // Блочна модель + // Box model display: flex; flex-direction: column; justify-content: center; @@ -358,40 +341,39 @@ layout: default width: 100px; height: 100px; - // Типографика + // Typography font: normal 14px "Helvetica Neue", sans-serif; line-height: 1.5; color: #333; text-align: center; text-decoration: underline; - // Візуалізація + // Visual background-color: #f5f5f5; border: 1px solid #e5e5e5; border-radius: 3px; - // Інше + // Misc opacity: 1; } ```
-### Булеві властивості -{: #logical-properties} +### Logical properties -Булеві властивості є альтернативою властивостям напрямку і розміру, таких як *блоковий* і *рядковий*. За замовчуванням блок відноситься до вертикального напрямку (з гори до низу), тоді як рядковий відноситься до горизонтального напрямку (праворуч і ліворуч). Ви можете почати використовувати ці значення у своєму CSS у всіх сучасних браузерах. +Logical properties are alternatives to directional and dimensonal properties based on abstract terms like *block* and *inline*. By default, block refers to the vertical direction (top and bottom) while inline refers to the horizontal direction (right and left). You can begin to use these values in your CSS in all modern, evergreen browsers. -**Навіщо використовувати булеві властивості?** Не в кожній мові написання йде з ліва на право, як в українській, тому [режим написання](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode) має бути гнучким. За допомогою булевих властивостей ви можете легко підтримувати мови, які можна писати горизонтально або вертикально (наприклад, китайську, японську та корейську). Крім того, вони зазвичай коротші та простіші для написання. +**Why use logical properties?** Not every language flows left-ro-right like English, so the [writing mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode) needs to be flexible. With logical properties, you can easily support languages that can be written horizontally or vertically (like Chinese, Japanese, and Korean). Plus, they're usually shorter and simpler to write. -**Додаткове читання:** +**Additional reading:** - [CSS Logical Properties and Values – MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Logical_Properties) -- [CSS Logical Properties and Values – CSS Tricks](https://css-tricks.com/css-logical-properties-and-values/) +- [CSS Logical Properties and Values — CSS Tricks](https://css-tricks.com/css-logical-properties-and-values/) - [CSS Writing Modes – MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Writing_Modes)
```scss -// Без булевих властивостей +// Without logical properties .element { margin-right: auto; margin-left: auto; @@ -399,7 +381,7 @@ layout: default border-bottom: 1px solid #eee; } -// З булевими властивостями +// With logical properties .element { margin-inline: auto; border-block: 1px solid #eee; @@ -407,14 +389,13 @@ layout: default ```
-### Кольори -{: #colors-section} +### Colors -Завдяки підтримці [CSS Color Levels 4](https://www.w3.org/TR/css-color-4/) [у ​​всіх основних браузерах](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb#space-separated_values) `rgba()` і `hsla()` тепер є тотожніми з `rgb()` і `hsl()`, тобто ви можете змінювати альфа-значення (прозорість) в `rgb()` і `hsl()`. Разом із цим з'являється підтримка нового синтаксису значень кольорів, розділених пробілами. Для сумісності з майбутніми функціями кольорів CSS використовуйте цей новий синтаксис. +With the support of [CSS Color Levels 4](https://www.w3.org/TR/css-color-4/) [in all major browsers](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb#space-separated_values), `rgba()` and `hsla()` are now aliases for `rgb()` and `hsl()`, meaning you can modify alpha values in `rgb()` and `hsl()`. Along with this comes support for new space-separated syntax for color values. For compability with future CSS color functions, use this new syntax. -Незалежно від ваших значень кольорів і синтаксису, завжди переконайтеся, що вибрані кольори відповідають [мінімальному коефіцієнту контрастності WCAG](https://webaim.org/articles/contrast/) (4.5:1 для шрифта 16 пікселів і менше, 3:1 для більших шрифтів). +Regardless of your color values and syntax, always ensure your color choices meet [WCAG minimum contrast ratios](https://webaim.org/articles/contrast/) (4.5:1 for 16px and smaller, 3:1 for larger). -**Додаткове читання:** +**Additional reading:** - [Smashing Magazine - A Guide To Modern CSS Colors](https://www.smashingmagazine.com/2021/11/guide-modern-css-colors/) - [`rgb()` - MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/rgb) @@ -428,33 +409,31 @@ layout: default ```
-### Уникайте використання `@import` -{: #avoid-imports} +### Avoid `@import`s -Порівняно з ``, `@import` повільніший, генерує додаткові запити ресурсів і може спричинити інші непередбачені проблеми. Уникайте їх і замість цього оберіть альтернативний підхід: +Compared to ``s, `@import` is slower, adds extra page requests, and can cause other unforeseen problems. Avoid them and instead opt for an alternate approach: -- Використовуйте кілька елементів `` -- Компілюйте свій CSS за допомогою препроцесора, наприклад [Sass](https://sass-lang.com/) або [Less](https://lesscss.org/), в один файл -- Об’єднайте свої файли CSS в один за допомогою функцій, доступних в Node.js, Rails, Jekyll та інших середовищах +- Use multiple ``elements +- Compile your CSS with a preprocessor like [Sass](https://sass-lang.com/) or [Less](https://lesscss.org/) into a single file +- Concatenate your CSS files with features provided in Rails, Jekyll, and other environments -Для отримання додаткової інформації [прочитайте цю статтю Стіва Соудерса](https://www.stevesouders.com/blog/2009/04/09/dont-use-import/). +For more information, [read this article by Steve Souders](https://www.stevesouders.com/blog/2009/04/09/dont-use-import/).
```html - + - + ```
-### Розміщення `@media` -{: #media-query-placement} +### Media query placement -Розташовуйте `@media` запити якомога ближче до відповідних наборів правил, коли це можливо. Не об’єднуйте їх усі в окрему таблицю стилів або в кінці документа. Це лише полегшить людям сумувати за ними в майбутньому. Ось типове налаштування. +Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.
```css @@ -470,34 +449,35 @@ layout: default ```
-### Одиночні декларації -{: #single-declarations} +### Single declarations -У випадках, коли набір правил містить **лише одну декларацію**, подумайте про видалення розривів рядків для зручності читання та швидшого редагування. Будь-який набір правил із декількома оголошеннями має бути розділений на окремі рядки. +In instances where a rule set includes **only one declaration**, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines. -Ключовим фактором тут є виявлення помилок, наприклад, валідатор CSS повідомляє, що у вас є синтаксична помилка в рядку 183. За допомогою однієї декларації її неможливо пропустити. З кількома деклараціями окремі рядки є обов’язковими для вашого розуму. +The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.
```scss -// Одиночні декларації в один рядок +// Single declarations on one line .span1 { width: 60px; } .span2 { width: 140px; } .span3 { width: 220px; } -// Декілька декларацій, кожна займає свій рядок +// Multiple declarations, one per line .sprite { display: inline-block; width: 16px; height: 15px; background-image: url("../img/sprite.png"); } +.icon { background-position: 0 0; } +.icon-home { background-position: 0 -20px; } +.icon-account { background-position: 0 -40px; } ```
-### Скорочена нотація -{: #shorthand-notation} +### Shorthand notation -Обмежте використання скорочених декларацій випадками, коли ви повинні явно встановити всі доступні значення. Часто використовувані скорочені властивості включають: +Limit shorthand declaration usage to instances where you must explicitly set all available values. Frequently overused shorthand properties include: - `padding` - `margin` @@ -506,15 +486,15 @@ layout: default - `border` - `border-radius` -Зазвичай нам не потрібно встановлювати всі значення, які представляє скорочена властивість. Наприклад, заголовки HTML встановлюють лише верхнє та нижнє значення `margin`, тому, коли необхідно, замінюйте лише ці два значення. Значення `0` означає заміну стандартного значення браузера або попереднього значення. +Usually we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. A `0` value implies an override of either a browser default or previously specified value. -Надмірне використання скорочених властивостей призводить до більш неохайного коду з непотрібними замінами та ненавмисними побічними ефектами. +Excessive use of shorthand properties leads to sloppier code with unnecessary overrides and unintended side effects. -Mozilla Developer Network має чудову статтю про [скорочені властивості](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties) для тих, хто не знайомий із цією нотацією. +The Mozilla Developer Network has a great article on [shorthand properties](https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties) for those unfamiliar with notation and behavior.
```scss -// Поганий приклад +// Bad example .element { margin: 0 0 10px; background: red; @@ -522,7 +502,7 @@ Mozilla Developer Network має чудову статтю про [скороч border-radius: 3px 3px 0 0; } -// Гарний приклад +// Good example .element { margin-bottom: 10px; background-color: red; @@ -533,132 +513,122 @@ Mozilla Developer Network має чудову статтю про [скороч ```
-### Вкладеність в препроцесорах -{: #nesting-in-preprocessors } +### Nesting in preprocessors -За можливості уникайте непотрібної вкладеності в препроцесорах — будьте простими та уникайте зворотного вкладення. Розглядайте вкладеніcть лише в тому випадку, якщо ви повинні застосувати стилі до батьківського елемента та якщо для вкладення є кілька елементів. +Avoid unnecessary nesting in preprocessors whenever possible—keep it simple and avoid reverse nesting. Consider nesting only if you must scope styles to a parent and if there are multiple elements to be nested. -**Додаткове читання:** -- [Вкладеність в Sass і Less](https://markdotto.com/2015/07/20/css-nesting/) +**Additional reading:** + +- Nesting in Sass and Less
```scss -// Без вкладеності -.table > thead > tr > th { ... } -.table > thead > tr > td { ... } +// Without nesting +.table > thead > tr > th { … } +.table > thead > tr > td { … } -// З вкладеністю +// With nesting .table > thead > tr { - > th { ... } - > td { ... } -} - -// Зворотна вкладеність - це дуже спантеличує -.child { - .parent & { ... } + > th { … } + > td { … } } ```
-### Оператори в препроцесорах -{: #operators-in-preprocessors } +### Operators in preprocessors -Для кращої читабельності візьміть усі математичні операції в дужки з одним пробілом між значеннями, змінними й операторами. +For improved readability, wrap all math operations in parentheses with a single space between values, variables, and operators.
```scss -// Поганий приклад +// Bad example .element { margin: 10px 0 @variable*2 10px; } -// Гарний приклад +// Good example .element { margin: 10px 0 (@variable * 2) 10px; } ```
-### Коментарі -{: #comments } +### Comments -Код пишуть і підтримують люди. Переконайтеся, що ваш код є само-описовим, добре прокоментованим і зрозумілим для інших. Чудові коментарі до коду передають контекст або мету. Не повторюйте просто назву компонента чи класу. Використовуйте `//` синтаксис під час написання CSS із препроцесорами. Під час підготовки CSS для продакшена видаліть усі коментарі. +Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name. Use the `//` syntax when writing CSS with preprocessors. When shipping CSS to production, remove all comments. -Великі коментарі обов’язково пишіть повними реченнями, а примітки - короткими фразами. +Be sure to write in complete sentences for larger comments and succinct phrases for general notes.
```scss -// Поганий приклад -// Модальний заголовок +// Bad example +// Modal header .modal-header { ... } -// Гарний приклад -// Елемент-обгортка для .modal-title та .modal-close +// Good example +// Wrapping element for .modal-title and .modal-close .modal-header { ... } ```
-### Імена класів -{: #class-names } +### Class names -- Зберігайте класи в нижньому регістрі та використовуйте тире (а не підкреслення або [верблюдячийРегістр](https://uk.wikipedia.org/wiki/%D0%92%D0%B5%D1%80%D0%B1%D0%BB%D1%8E%D0%B4%D1%8F%D1%87%D0%B8%D0%B9_%D1%80%D0%B5%D0%B3%D1%96%D1%81%D1%82%D1%80)). Тире служать природними розривами у пов’язаному класі (наприклад, `.btn` і `.btn-danger`). -- Уникайте надмірних і довільних скорочень. `.btn` корисний для кнопки, але `.s` нічого не означає. -- Робіть класи максимально короткими та лаконічними. -- Використовуйте змістовні імена; використовувайте структурні або цільові назви замість презентаційних. -- Додавайте префікси до класів на основі найближчого батьківського або базового класу. -- Використовуйте класи `.js-*` для позначення поведінки (на відміну від стилю), але не використовуйте ці класи у своєму CSS. +- Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g., `.btn` and `.btn-danger`). +- Avoid excessive and arbitrary shorthand notation. `.btn` is useful for _button_, but `.s` doesn't mean anything. +- Keep classes as short and succinct as possible. +- Use meaningful names; use structural or purposeful names over presentational. +- Prefix classes based on the closest parent or base class. +- Use `.js-*` classes to denote behavior (as opposed to style), but keep these classes out of your CSS. -Також корисно застосовувати багато з цих самих правил під час створення настроюваних властивостей і імен змінних препроцесора. +It's also useful to apply many of these same rules when creating custom properties and preprocessor variable names.
```scss -// Поганий приклад +// Bad example .t { ... } .red { ... } .header { ... } -// Гарний приклад +// Good example .tweet { ... } .important { ... } .tweet-header { ... } ```
-### Селектори -{: #selectors} +### Selectors -- Використовуйте класи замість загальних тегів елементів для більш чіткого та надійного стилю, який не залежить від вашої розмітки. -- Уникайте використання кількох селекторів атрибутів (наприклад, `[class^="..."]`) для часто зустрічаються компонентів. Відомо, що це впливає на продуктивність браузера. -- Зберігайте селектори короткими та намагайтеся обмежити кількість елементів у кожному селекторі до трьох. -- Звужуйте дію класів до найближчого батьківського елемента **лише** за необхідності (наприклад, коли не використовуються префіксовані класи). +- Use classes over generic element tags for more explicit and reliable styling that isn't dependent on your markup. +- Avoid using several attribute selectors (e.g., `[class^="..."]`) on commonly occuring components. Browser performance is known to be impacted by these. +- Keep selectors short and strive to limit the number of elements in each selector to three. +- Scope classes to the closest parent `only` when necessary (e.g., when not using prefixed classes). -**Додаткове читання:** +**Additional reading:** - [Scope CSS classes with prefixes](https://markdotto.com/2012/02/16/scope-css-classes-with-prefixes/) - [Stop the cascade](https://markdotto.com/2012/03/02/stop-the-cascade/)
```scss -// Поганий приклад +// Bad example span { ... } .page-container #stream .stream-item .tweet .tweet-header .username { ... } .avatar { ... } -// Гарний приклад +// Good example .avatar { ... } .tweet-header .username { ... } .tweet .avatar { ... } ```
-### Дочірні та нащадкові селектори -{: #child-and-descendant-selectors } +### Child and descendant selectors -За потреби може бути корисним використовувати [дочірній комбінатор (>)](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator), щоб обмежити каскад деяких стилів у таких елементах, як ``, які часто є рекурсивно вкладеними. Використовуйте його, щоб обмежити стилі безпосередніми дочірніми елементами батьківського елемента, щоб уникнути непотрібних перевизначень пізніше. +When necessary, it may be helpful to use [the child combinator (`>`)](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator) to limit the cascade of some styles in elements like `
`s that are often recursively nested. Use it to limit styles to the immediate children elements of a parent element to avoid unnecessary overrides later on. ```css @@ -669,31 +639,30 @@ span { ... } ```
-### Організація -{: #organization } +### Organization -- Упорядкуйте розділи коду за компонентами. -- Розробіть послідовну ієрархію коментарів. -- Використовуйте однакові відступи, коли розділяєте частини коду для просмотру документів більшого розміру. -- Використовуючи кілька файлів CSS, розбийте їх за компонентами, а не за сторінками. Сторінки можна переставляти, а компоненти переміщувати. +- Organize sections of code by component. +- Develop a consistent commenting hierarchy. +- Use consistent white space to your advantage when separating sections of code for scanning larger documents. +- When using multiple CSS files, break them down by component instead of page. Pages can be rearranged and components moved.
```scss // -// Заголовок секції компонента +// Component section heading // .element { ... } // -// Заголовок секції компонента +// Component section heading // -// Іноді потрібно включити додатковий контекст для всього компонента. Зробіть це тут, якщо це досить важливо. +// Sometimes you need to include optional context for the entire component. Do that up here if it's important enough. // .element { ... } -// Дочірній компонент або модифікатор +// Contextual sub-component or modifer .element-heading { ... } ```