From daa1a2aff136fa9da1fcc97d7da97a2036fabc77 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:51:47 +0100 Subject: unslug uk: move --- .../uk/web/css/alternative_style_sheets/index.html | 80 +++++ .../css_animations/using_css_animations/index.html | 357 +++++++++++++++++++ .../index.html" | 357 ------------------- files/uk/web/css/css_box_model/index.html | 161 +++++++++ .../mastering_margin_collapsing/index.html | 90 +++++ .../index.html" | 90 ----- .../basic_concepts_of_flexbox/index.html | 391 +++++++++++++++++++++ .../using_css_flexible_boxes/index.html | 391 --------------------- files/uk/web/css/layout_cookbook/index.html | 80 +++++ files/uk/web/css/layout_mode/index.html | 30 ++ files/uk/web/css/reference/index.html | 188 ++++++++++ .../uk/web/css/visual_formatting_model/index.html | 225 ++++++++++++ .../index.html" | 80 ----- .../index.html" | 188 ---------- .../index.html" | 161 --------- .../index.html" | 225 ------------ .../index.html" | 80 ----- .../index.html" | 30 -- 18 files changed, 1602 insertions(+), 1602 deletions(-) create mode 100644 files/uk/web/css/alternative_style_sheets/index.html create mode 100644 files/uk/web/css/css_animations/using_css_animations/index.html delete mode 100644 "files/uk/web/css/css_animations/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_css_\320\260\320\275\321\226\320\274\320\260\321\206\321\226\320\271/index.html" create mode 100644 files/uk/web/css/css_box_model/index.html create mode 100644 files/uk/web/css/css_box_model/mastering_margin_collapsing/index.html delete mode 100644 "files/uk/web/css/css_box_model/\320\267\320\263\320\276\321\200\321\202\320\260\320\275\320\275\321\217_\320\262\321\226\320\264\321\201\321\202\321\203\320\277\321\226\320\262/index.html" create mode 100644 files/uk/web/css/css_flexible_box_layout/basic_concepts_of_flexbox/index.html delete mode 100644 files/uk/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html create mode 100644 files/uk/web/css/layout_cookbook/index.html create mode 100644 files/uk/web/css/layout_mode/index.html create mode 100644 files/uk/web/css/reference/index.html create mode 100644 files/uk/web/css/visual_formatting_model/index.html delete mode 100644 "files/uk/web/css/\320\260\320\273\321\214\321\202\320\265\321\200\320\275\320\260\321\202\320\270\320\262\320\275\321\226_\321\202\320\260\320\261\320\273\320\270\321\206\321\226_\321\201\321\202\320\270\320\273\321\226\320\262/index.html" delete mode 100644 "files/uk/web/css/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" delete mode 100644 "files/uk/web/css/\320\272\320\276\321\200\320\276\320\261\321\207\320\260\321\201\321\202\320\260_\320\274\320\276\320\264\320\265\320\273\321\214_css/index.html" delete mode 100644 "files/uk/web/css/\320\274\320\276\320\264\320\265\320\273\321\214_\320\262\321\226\320\267\321\203\320\260\320\273\321\214\320\275\320\276\320\263\320\276_\321\204\320\276\321\200\320\274\321\203\320\262\320\260\320\275\320\275\321\217/index.html" delete mode 100644 "files/uk/web/css/\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260_\320\272\321\203\320\273\321\226\320\275\320\260\321\200\320\275\320\260-\320\272\320\275\320\270\320\263\320\260/index.html" delete mode 100644 "files/uk/web/css/\321\201\321\205\320\265\320\274\320\260_\320\272\320\276\320\274\320\277\320\276\320\275\321\203\320\262\320\260\320\275\320\275\321\217/index.html" (limited to 'files/uk/web/css') diff --git a/files/uk/web/css/alternative_style_sheets/index.html b/files/uk/web/css/alternative_style_sheets/index.html new file mode 100644 index 0000000000..1dd1b5a510 --- /dev/null +++ b/files/uk/web/css/alternative_style_sheets/index.html @@ -0,0 +1,80 @@ +--- +title: Альтернативні таблиці стилів +slug: Web/CSS/Альтернативні_таблиці_стилів +tags: + - Стилі + - Теми +translation_of: Web/CSS/Alternative_style_sheets +--- +

Specifying alternative style sheets in a web page provides a way for users to see multiple versions of a page, based on their needs or preferences.

+ +

Firefox lets the user select the stylesheet using the View > Page Style submenu, Internet Explorer also supports this feature (beginning with IE 8), also accessed from View > Page Style (at least as of IE 11), but Chrome requires an extension to use the feature (as of version 48). The web page can also provide its own user interface to let the user switch styles.

+ +

An example: specifying the alternative stylesheets

+ +

The alternate stylesheets are commonly specified using a {{HTMLElement("link")}} element with rel="stylesheet alternate" and title="..." attributes, for example:

+ +
<link href="reset.css" rel="stylesheet" type="text/css">
+
+<link href="default.css" rel="stylesheet" type="text/css" title="Default Style">
+<link href="fancy.css" rel="alternate stylesheet" type="text/css" title="Fancy">
+<link href="basic.css" rel="alternate stylesheet" type="text/css" title="Basic">
+
+ +

In this example, the styles "Default Style", "Fancy", and "Basic" will be listed in the Page Style submenu, with the Default Style pre-selected. When the user selects a different style, the page will immediately be re-rendered using that style sheet.

+ +

No matter what style is selected, the rules from the reset.css stylesheet will always be applied.

+ +

Try it out

+ +

Click here for a working example you can try out.

+ +

Details

+ +

Any stylesheet in a document falls into one of the following categories:

+ + + +

When style sheets are referenced with a title attribute on the {{HTMLElement("link", "<link rel=\"stylesheet\">")}} or {{HTMLElement("style")}} element, the title becomes one of the choices offered to the user. Style sheets linked with the same title are part of the same choice. Style sheets linked without a title attribute are always applied.

+ +

Use rel="stylesheet" to link to the default style, and rel="alternate stylesheet" to link to alternative style sheets. This tells the browser which style sheet title should be selected by default, and makes that default selection apply in browsers that do not support alternate style sheets.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#css-style-sheet-collections', 'CSS Style Sheet Collections')}}{{Spec2('CSSOM')}}The CSS OM specification defines the concepts of the style sheet set name, its disabled flag, and the preferred CSS style sheet set name.
+ It defines how these are determined, and lets the HTML specification define the HTML-specific behaviors by requiring it to define when to create a CSS style sheet.
+

{{SpecName('HTML WHATWG', 'semantics.html#link-type-stylesheet', 'Link type "stylesheet"')}}
+ {{SpecName('HTML WHATWG', 'semantics.html#attr-style-title', 'The style element')}}
+ {{SpecName('HTML WHATWG', 'semantics.html#attr-meta-http-equiv-default-style', 'Default style state (http-equiv="default-style")')}}

+
{{Spec2('HTML WHATWG')}}The HTML specification defines when and how the create a CSS style sheet algorithm is invoked while handling <link> and <style> elements, and also defines the behavior of <meta http-equiv="default-style">.
{{SpecName("HTML4.01", "present/styles.html#h-14.3", "Alternative style sheets")}}{{Spec2("HTML4.01")}}Earlier, the HTML specification itself defined the concept of preferred and alternate stylesheets.
+ +

 

diff --git a/files/uk/web/css/css_animations/using_css_animations/index.html b/files/uk/web/css/css_animations/using_css_animations/index.html new file mode 100644 index 0000000000..f8b8466ef4 --- /dev/null +++ b/files/uk/web/css/css_animations/using_css_animations/index.html @@ -0,0 +1,357 @@ +--- +title: Використання CSS анімацій +slug: Web/CSS/CSS_Animations/Використання_CSS_анімацій +tags: + - CSS Animations + - Довідка +translation_of: Web/CSS/CSS_Animations/Using_CSS_animations +--- +

{{SeeCompatTable}}{{CSSRef}}

+ +

CSS анімації роблять можливим анімацію переходів (transitions) з однєї конфігурації CSS стилю до іншої. Анімації складаються з двох компонентів, а власне - стилю, котрий описує CSS анімацію та набір ключових кадрів (keyframes), які задають початковий та кінцевий стан стилю анімації, а також є можливим задання точок проміжного стану.

+ +

В CSS анімацій є три ключові переваги перед традиційними скриптовими техніками анімації:

+ +
    +
  1. Вони легкі у використанні для простих анімацій; ви можете створити їх навіть без знань JavaScript.
  2. +
  3. Анімації добре функціонують, навіть при помірному навантаженні на систему. Прості анімації на JavaScript можуть працювати не дуже добре (в разі, якщо вони не ідеально зроблені). Движок рендера може використовувати техніку пропуску кадрів та інші засоби для підтримки гладкої анімації.
  4. +
  5. Надаючи таким чином браузеру контроль над послідовністю анімації ви надаєте можливість брауцзеру оптимізувати свою роботу та ефективність, наприклад, завдяки зупинці анімації у вкладках, які не є відкриті для перегляду.
  6. +
+ +

Конфігурування анімації

+ +

Щоб створити CSS-анімаційну послідвність, ви стилізуєте анімований елемент {{ cssxref("animation") }} властивістю чи її підвластивостями. Це дозвоялє вам коригувати таймінг, тривалість та інші деталі анімації згідно з вашими потребами. Це не конфігурує актуальний вигляд анімації, яка здійснюється проходом через {{ cssxref("@keyframes") }} at-правила, як це описано в {{ anch("Визначення послідовності анімації через ключові кадри") }} нижче.

+ +

Підвластивостями властивості {{ cssxref("animation") }} є:

+ +
+
{{ cssxref("animation-delay") }}
+
Змінює час затримки між часом з моменту завантаження елемента та початком анімаційної послідовності.
+
{{ cssxref("animation-direction") }}
+
Визначає зміну напрямку анімації та його чергування в залежності від кількості проходів анімації, а також може задавати повернення в початковий стан і починати прохід заново.
+
{{ cssxref("animation-duration") }}
+
Визначає тривалість циклу анімації.
+
{{ cssxref("animation-iteration-count") }}
+
Визначає кількість проходів (повторів) анімації; ви можете також обрати значення infinite для нескінченного повтору анімації.
+
{{ cssxref("animation-name") }}
+
Задає ім'я для анімації {{ cssxref("@keyframes") }} через at-правило, яке описує анімаційні ключові кадри.
+
{{ cssxref("animation-play-state") }}
+
Дозволяє вам призупиняти та відновлювати анімацію.
+
{{ cssxref("animation-timing-function") }}
+
Задає конфігурацію таймінгу анімації; інакше кажучи, як саме буде анімація робити прохід через ключові кадри, це можливо завдяки кривим прискорення.
+
{{ cssxref("animation-fill-mode") }}
+
Визначає, які значення будуть застосовані для анімації перед початком та після її закінчення.
+
+ +

Визначення послідовності анімації через ключові кадри

+ +

Опісля того, як ви задали анімації таймінг, вам потрібно задати вигляд анімації. Це робиться завдяки одному чи більше  ключовому кадру шляхом застосування at-правила {{ cssxref("@keyframes") }}. Кожен ключовий кадр описує, як саме повинен відображатися анімований елемент у певний момент під час проходження анімаційної послідовності.

+ +

Після того, як таймінг анімації був заданий в CSS стилі, який конгфігурує анімацію, ключові кадри використовують {{ cssxref("percentage") }} для відображення моменту під час анімації, в якому буде розміщений той чи інший ключовий кадр. 0% вказує на сам початок анімаціїйної послідовності, тоді як 100% вказує на завершальний етап анімації. Оскільки ці два моменти є такими важливими, вони мають свої спеціальні імена: from і to відповідно. Обидва ці імені є необов'язковими. Якщо from/0% чи to/100% не є задано, то браузер починає чи зупиняє анімацію використовуючи середньообраховані значення всіх атрибутів.

+ +

Ви також можете на свій розсуд додавати проміжні кадри до анімації, аби описати стан анімації в проміжні періоди.

+ +

Приклади

+ +
Примітка: Подані приклади не використовують вендорних префіксів. WebKit-браузери та старіші версії інших браузерів можуть потребувати цих префіксів; приклади, на які ви можете клацнути для перегляду у вашому браузері також включають -webkit-префіксовані версії.
+ +

Текст, що ковзає у вікні браузера

+ +

Цей простий приклад стилізує елемент {{ HTMLElement("p") }} так, що текст "зісковзує" в вікно браузера з-поза його правого краю.

+ +

Майте на увазі, що такі анімації можуть робити сторінку ширшою, аніж вікно браузера. Аби уникнути такої проблеми, потрібно помістити анімований елемент в контейнер і встановити для останнього {{cssxref("overflow")}}:hidden.

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+}
+
+@keyframes slidein {
+  from {
+    margin-left: 100%;
+    width: 300%;
+  }
+
+  to {
+    margin-left: 0%;
+    width: 100%;
+  }
+}
+
+ +

В цьому прикладі стиль для {{ HTMLElement("p") }}-елемента визначає, що тривалість анімації становить 3 секунди від початку до кінця, використовуючи властивість {{ cssxref("animation-duration") }}, а також присвоює ім'я цій анімації, яке використано у ключових кадрах {{ cssxref("@keyframes") }} . Їхні at-правила визначили, що це ключові кадри для анімації, яка називається “slidein”.

+ +

Якщо нам потрібно ще якусь додаткову стилізацію елемента {{ HTMLElement("p") }} для відобаження в браузерах, які не підтримують CSS анімацій, то ми б її включили туди ж; однак, в цьому випадку ми не потребуємо додаткової стилізації, крім анімації елемента.

+ +

Ключові кадри визначені через  at-правила {{ cssxref("@keyframes") }}. В даному випадку є лише два ключових кадри. Перший ключовий кадр наступає в 0% (вжито спеціальне ім'я from). Тут, ми змінюємо лівий маргін елемента як 100% (тобто це відраховується, як відстань від правого краю контейнера), і встановили 300% ширини для елемента (Втричі ширше за контейнер). Завдяки цьому на першому ключовому кадрі анімований елемент буде знаходитися поза межами контейнера (вікна браузера).

+ +

Другий ключовий кадр (він же завершальний) розміщений на завершенні анімації, 100% (спеціальне ім'я to). Лівий маргін встановлено як 0% і ширину елемента ми встановили як 100%. Це спричиняє "приклеювання" елемента до лівого краю вікна браузера.

+ +
<p>The Caterpillar and Alice looked at each other for some time in silence:
+at last the Caterpillar took the hookah out of its mouth, and addressed
+her in a languid, sleepy voice.</p>
+
+ +

(Перезавантажте сторінку, аби побачити анімацію, або ж клікніть на кнопку CodePen, щоб побачити анімацію в середовищі CodePen)

+ +

{{EmbedLiveSample("Making_text_slide_across_the_browser_window","100%","250")}}

+ +

Додавання інших ключових кадрів

+ +

Давайте додамо ще один ключовий кадр до анімації з попереднього прикладу. Припустимо, нам потрібно трішки збільшити шрифт, коли текст рухається вліво, а потім ми його повертаємо до попередніх параметрів. Це просто, як додавання ось такого ключового кадру:

+ +
75% {
+  font-size: 300%;
+  margin-left: 25%;
+  width: 150%;
+}
+
+ + + + + +

Це повідомляє браузеру, що елемент, при виконанні 75% анімації, повинен мати лівий маргін 25% і ширину 150%.

+ +

(Перезавантажте сторінку, аби побачити анімацію, або ж клікніть на конпку CodePen, щоб побачити анімацію в середовищі CodePen)

+ +

{{EmbedLiveSample("Adding_another_keyframe","100%","250")}}

+ +

Making it repeat

+ +

Якщо вам потрібно, аби анімація повторювалась, просто використайте властивість  {{ cssxref("animation-iteration-count") }} , щоб зазначити, скільки разів повинна повторитися анімація. В даному випадку давайте використаємо значення infinite для отримання постійної анімації:

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+}
+
+ + + + + +

{{EmbedLiveSample("Making_it_repeat","100%","250")}}

+ +

Змінюємо напрямки анімації

+ +

Отже, анімація повторювана, але це виглядає дивно: текст по завершенню циклу, з початком нового знову стрибає вбік. Отже нам треба зробити, аби текст плавно повертався назад, на початкову позицію. Це просто: прописуємо у {{ cssxref("animation-direction") }} значення alternate:

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+  animation-direction: alternate;
+}
+
+ + + + + +

{{EmbedLiveSample("Making_it_move_back_and_forth","100%","250")}}

+ +

Використання скорочень для правил анімації

+ +

{{ cssxref("animation") }} скорочення є вигідним для економії місця. От, для прикладу, правила анімації, які ми вже використали в статті:

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+  animation-direction: alternate;
+}
+
+ +

Їх можна замінити ось таким чином

+ +
p {
+  animation: 3s infinite alternate slideIn;
+}
+ +
+

Примітка: Ви можете дізнатися про це більше на сторінці довідки {{ cssxref("animation") }} :

+
+ +

Задання множинних значень властивостей анімації

+ +

Нескорочені значення CSS анімації можуть приймати множинні значення, розділені комами — таку особливість можна використати, якщо вам потрібно задати множинні анімації єдиним набором правил і відповідно задати різні тривалості, повтори і так далі для різних анімацій. Давайте глянемо на кілька швидких прикладів, аби пояснити різні зміни:

+ +

В першому прикладі у нас є набір з трьох різних імен анімації, але одна й та ж тривалість і кількість повторів:

+ +
animation-name: fadeInOut, moveLeft300px, bounce;
+animation-duration: 3s;
+animation-iteration-count: 1;
+ +

В другому прикладі в нас є набір з 3х значень для кожної властивості. В цьому випадку кожна анімація буде здійснюватися з відповідними значеннями, згідно з їх розміщенням у властивостях, то ж, приміром, fadeInOut має тривалість в 2.5s і кількість повторів 2,  і т.д..

+ +
animation-name: fadeInOut, moveLeft300px, bounce;
+animation-duration: 2.5s, 5s, 1s;
+animation-iteration-count: 2, 1, 5;
+ +

У цьому третьому випадку є три різні анімації, але лише дві різні тривалості та кількості повторів. У таких випадках наборів значень недостатньо, то ж кожна анімація отримає свій набір значень шляхом перебору від початку до кінця. Наприклад, fadeInOut отримає тривалість в 2.5s і moveLeft300px матиме тривалість 5s. Набори значень на цьому закінчились, тому все починається з початку і третя анімація bounce отримає тривалість знову в 2.5s. Кількість повторів (та й будь-які інші значення властивостей, які ви задасте) будуть присвоєні такими самим чином.

+ +
animation-name: fadeInOut, moveLeft300px, bounce;
+animation-duration: 2.5s, 5s;
+animation-iteration-count: 2, 1;
+ +

Використання подій анімації

+ +

Ви можете отримати додатковий контроль над анімаціями, як і корисну інформацію про них шляхом використання подій анімації. Ці події, представлені об'єктом {{ domxref("AnimationEvent") }}, можуть бути використані, аби визначити, коли починаються, закінчуються і починають новий повтор різні анімації. Кожна подія містить час, о котрій вона сталась та ім'я анімації, яка її запустила.

+ +

Зараз ми змінимо приклад з ковзаючим текстом, аби вивести певну інформацію про кожну анімаційну подію, тобто її час, то ж ми можемо розібратися, як вони працюють.

+ +

Додавання CSS

+ +

Починаємо зі створення CSS для анімації. Дана анімація триватиме 3 секунди, назвемо її “slidein”, задамо повтор 3 рази, і напрям анімації alternate кожного разу. В {{ cssxref("@keyframes") }}, ширина і лівий маргін змінюються, щоб текст ковзав по екрану.

+ +
.slidein {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: 3;
+  animation-direction: alternate;
+}
+
+@keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+    margin-left:0%;
+    width:100%;
+  }
+}
+ +

Встановлення animation event listeners - прослуховування подій анімації

+ +

Ми використаємо код JavaScript для прослуховування всіх трьох можливих подій анімації. Даний код задає наші event listeners; ми викликаємо його, коли документ вперше завантажений, для того, щоб отримати впорядковані дані.

+ +
var e = document.getElementById("watchme");
+e.addEventListener("animationstart", listener, false);
+e.addEventListener("animationend", listener, false);
+e.addEventListener("animationiteration", listener, false);
+
+e.className = "slidein";
+
+ +

Це цілком звичайний код, аби дізнатися більше, ви можете звіритися з документацією {{ domxref("eventTarget.addEventListener()") }}. Останнє, що робить код - він задає клас анімованого елемента як “slidein”; це нам потрібно для запуску анімації.

+ +

Чому? Тому що подія animationstart запускається одразу ж, як стартує анімація; в даному випадку це стається до того, як починає діяти наш код. То ж ми починаємо анімацію самі, задаючи клас елементу для стиля, котрий буде анімований по факту.

+ +

Отримання подій

+ +

Події надсилаються до функції listener(), як це показано нижче.

+ +
function listener(e) {
+  var l = document.createElement("li");
+  switch(e.type) {
+    case "animationstart":
+      l.innerHTML = "Started: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationend":
+      l.innerHTML = "Ended: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationiteration":
+      l.innerHTML = "New loop started at time " + e.elapsedTime;
+      break;
+  }
+  document.getElementById("output").appendChild(l);
+}
+
+ +

Даний код також дуже простий. Він просто дивиться в {{ domxref("event.type") }}, аби визначити, який власне тип події анімації трапився, тоді додає відповідну примітку в {{ HTMLElement("ul") }} (невпорядкований список), який ми використовуємо для виводу звіту про ці події.

+ +

Звіт після завершення роботи буде виглядати якось от так:

+ + + +

Зауважте, що часи подій досить точні щодо тих, які ми очікували відповідно до таймінгу, який ми задали, коли створювали анімацію. Візьміть до уваги також і те, що після завершального проходу анімації подія animationiteration не була надіслана; натомість надіслало подію animationend.

+ +

HTML

+ +

Чисто для повної завершеності огляду ось код, який відображає контент сторіки, включно зі списком звіту про події анімації, який створився завдяки вищеописаному скрипту:

+ +
<h1 id="watchme">Watch me move</h1>
+<p>
+  This example shows how to use CSS animations to make <code>H1</code>
+  elements move across the page.
+</p>
+<p>
+  In addition, we output some text each time an animation event fires,
+  so you can see them in action.
+</p>
+<ul id="output">
+</ul>
+</body>
+
+ +

{{EmbedLiveSample('Using_animation_events', '600', '300')}}

+ +

Дивіться також

+ + diff --git "a/files/uk/web/css/css_animations/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_css_\320\260\320\275\321\226\320\274\320\260\321\206\321\226\320\271/index.html" "b/files/uk/web/css/css_animations/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_css_\320\260\320\275\321\226\320\274\320\260\321\206\321\226\320\271/index.html" deleted file mode 100644 index f8b8466ef4..0000000000 --- "a/files/uk/web/css/css_animations/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_css_\320\260\320\275\321\226\320\274\320\260\321\206\321\226\320\271/index.html" +++ /dev/null @@ -1,357 +0,0 @@ ---- -title: Використання CSS анімацій -slug: Web/CSS/CSS_Animations/Використання_CSS_анімацій -tags: - - CSS Animations - - Довідка -translation_of: Web/CSS/CSS_Animations/Using_CSS_animations ---- -

{{SeeCompatTable}}{{CSSRef}}

- -

CSS анімації роблять можливим анімацію переходів (transitions) з однєї конфігурації CSS стилю до іншої. Анімації складаються з двох компонентів, а власне - стилю, котрий описує CSS анімацію та набір ключових кадрів (keyframes), які задають початковий та кінцевий стан стилю анімації, а також є можливим задання точок проміжного стану.

- -

В CSS анімацій є три ключові переваги перед традиційними скриптовими техніками анімації:

- -
    -
  1. Вони легкі у використанні для простих анімацій; ви можете створити їх навіть без знань JavaScript.
  2. -
  3. Анімації добре функціонують, навіть при помірному навантаженні на систему. Прості анімації на JavaScript можуть працювати не дуже добре (в разі, якщо вони не ідеально зроблені). Движок рендера може використовувати техніку пропуску кадрів та інші засоби для підтримки гладкої анімації.
  4. -
  5. Надаючи таким чином браузеру контроль над послідовністю анімації ви надаєте можливість брауцзеру оптимізувати свою роботу та ефективність, наприклад, завдяки зупинці анімації у вкладках, які не є відкриті для перегляду.
  6. -
- -

Конфігурування анімації

- -

Щоб створити CSS-анімаційну послідвність, ви стилізуєте анімований елемент {{ cssxref("animation") }} властивістю чи її підвластивостями. Це дозвоялє вам коригувати таймінг, тривалість та інші деталі анімації згідно з вашими потребами. Це не конфігурує актуальний вигляд анімації, яка здійснюється проходом через {{ cssxref("@keyframes") }} at-правила, як це описано в {{ anch("Визначення послідовності анімації через ключові кадри") }} нижче.

- -

Підвластивостями властивості {{ cssxref("animation") }} є:

- -
-
{{ cssxref("animation-delay") }}
-
Змінює час затримки між часом з моменту завантаження елемента та початком анімаційної послідовності.
-
{{ cssxref("animation-direction") }}
-
Визначає зміну напрямку анімації та його чергування в залежності від кількості проходів анімації, а також може задавати повернення в початковий стан і починати прохід заново.
-
{{ cssxref("animation-duration") }}
-
Визначає тривалість циклу анімації.
-
{{ cssxref("animation-iteration-count") }}
-
Визначає кількість проходів (повторів) анімації; ви можете також обрати значення infinite для нескінченного повтору анімації.
-
{{ cssxref("animation-name") }}
-
Задає ім'я для анімації {{ cssxref("@keyframes") }} через at-правило, яке описує анімаційні ключові кадри.
-
{{ cssxref("animation-play-state") }}
-
Дозволяє вам призупиняти та відновлювати анімацію.
-
{{ cssxref("animation-timing-function") }}
-
Задає конфігурацію таймінгу анімації; інакше кажучи, як саме буде анімація робити прохід через ключові кадри, це можливо завдяки кривим прискорення.
-
{{ cssxref("animation-fill-mode") }}
-
Визначає, які значення будуть застосовані для анімації перед початком та після її закінчення.
-
- -

Визначення послідовності анімації через ключові кадри

- -

Опісля того, як ви задали анімації таймінг, вам потрібно задати вигляд анімації. Це робиться завдяки одному чи більше  ключовому кадру шляхом застосування at-правила {{ cssxref("@keyframes") }}. Кожен ключовий кадр описує, як саме повинен відображатися анімований елемент у певний момент під час проходження анімаційної послідовності.

- -

Після того, як таймінг анімації був заданий в CSS стилі, який конгфігурує анімацію, ключові кадри використовують {{ cssxref("percentage") }} для відображення моменту під час анімації, в якому буде розміщений той чи інший ключовий кадр. 0% вказує на сам початок анімаціїйної послідовності, тоді як 100% вказує на завершальний етап анімації. Оскільки ці два моменти є такими важливими, вони мають свої спеціальні імена: from і to відповідно. Обидва ці імені є необов'язковими. Якщо from/0% чи to/100% не є задано, то браузер починає чи зупиняє анімацію використовуючи середньообраховані значення всіх атрибутів.

- -

Ви також можете на свій розсуд додавати проміжні кадри до анімації, аби описати стан анімації в проміжні періоди.

- -

Приклади

- -
Примітка: Подані приклади не використовують вендорних префіксів. WebKit-браузери та старіші версії інших браузерів можуть потребувати цих префіксів; приклади, на які ви можете клацнути для перегляду у вашому браузері також включають -webkit-префіксовані версії.
- -

Текст, що ковзає у вікні браузера

- -

Цей простий приклад стилізує елемент {{ HTMLElement("p") }} так, що текст "зісковзує" в вікно браузера з-поза його правого краю.

- -

Майте на увазі, що такі анімації можуть робити сторінку ширшою, аніж вікно браузера. Аби уникнути такої проблеми, потрібно помістити анімований елемент в контейнер і встановити для останнього {{cssxref("overflow")}}:hidden.

- -
p {
-  animation-duration: 3s;
-  animation-name: slidein;
-}
-
-@keyframes slidein {
-  from {
-    margin-left: 100%;
-    width: 300%;
-  }
-
-  to {
-    margin-left: 0%;
-    width: 100%;
-  }
-}
-
- -

В цьому прикладі стиль для {{ HTMLElement("p") }}-елемента визначає, що тривалість анімації становить 3 секунди від початку до кінця, використовуючи властивість {{ cssxref("animation-duration") }}, а також присвоює ім'я цій анімації, яке використано у ключових кадрах {{ cssxref("@keyframes") }} . Їхні at-правила визначили, що це ключові кадри для анімації, яка називається “slidein”.

- -

Якщо нам потрібно ще якусь додаткову стилізацію елемента {{ HTMLElement("p") }} для відобаження в браузерах, які не підтримують CSS анімацій, то ми б її включили туди ж; однак, в цьому випадку ми не потребуємо додаткової стилізації, крім анімації елемента.

- -

Ключові кадри визначені через  at-правила {{ cssxref("@keyframes") }}. В даному випадку є лише два ключових кадри. Перший ключовий кадр наступає в 0% (вжито спеціальне ім'я from). Тут, ми змінюємо лівий маргін елемента як 100% (тобто це відраховується, як відстань від правого краю контейнера), і встановили 300% ширини для елемента (Втричі ширше за контейнер). Завдяки цьому на першому ключовому кадрі анімований елемент буде знаходитися поза межами контейнера (вікна браузера).

- -

Другий ключовий кадр (він же завершальний) розміщений на завершенні анімації, 100% (спеціальне ім'я to). Лівий маргін встановлено як 0% і ширину елемента ми встановили як 100%. Це спричиняє "приклеювання" елемента до лівого краю вікна браузера.

- -
<p>The Caterpillar and Alice looked at each other for some time in silence:
-at last the Caterpillar took the hookah out of its mouth, and addressed
-her in a languid, sleepy voice.</p>
-
- -

(Перезавантажте сторінку, аби побачити анімацію, або ж клікніть на кнопку CodePen, щоб побачити анімацію в середовищі CodePen)

- -

{{EmbedLiveSample("Making_text_slide_across_the_browser_window","100%","250")}}

- -

Додавання інших ключових кадрів

- -

Давайте додамо ще один ключовий кадр до анімації з попереднього прикладу. Припустимо, нам потрібно трішки збільшити шрифт, коли текст рухається вліво, а потім ми його повертаємо до попередніх параметрів. Це просто, як додавання ось такого ключового кадру:

- -
75% {
-  font-size: 300%;
-  margin-left: 25%;
-  width: 150%;
-}
-
- - - - - -

Це повідомляє браузеру, що елемент, при виконанні 75% анімації, повинен мати лівий маргін 25% і ширину 150%.

- -

(Перезавантажте сторінку, аби побачити анімацію, або ж клікніть на конпку CodePen, щоб побачити анімацію в середовищі CodePen)

- -

{{EmbedLiveSample("Adding_another_keyframe","100%","250")}}

- -

Making it repeat

- -

Якщо вам потрібно, аби анімація повторювалась, просто використайте властивість  {{ cssxref("animation-iteration-count") }} , щоб зазначити, скільки разів повинна повторитися анімація. В даному випадку давайте використаємо значення infinite для отримання постійної анімації:

- -
p {
-  animation-duration: 3s;
-  animation-name: slidein;
-  animation-iteration-count: infinite;
-}
-
- - - - - -

{{EmbedLiveSample("Making_it_repeat","100%","250")}}

- -

Змінюємо напрямки анімації

- -

Отже, анімація повторювана, але це виглядає дивно: текст по завершенню циклу, з початком нового знову стрибає вбік. Отже нам треба зробити, аби текст плавно повертався назад, на початкову позицію. Це просто: прописуємо у {{ cssxref("animation-direction") }} значення alternate:

- -
p {
-  animation-duration: 3s;
-  animation-name: slidein;
-  animation-iteration-count: infinite;
-  animation-direction: alternate;
-}
-
- - - - - -

{{EmbedLiveSample("Making_it_move_back_and_forth","100%","250")}}

- -

Використання скорочень для правил анімації

- -

{{ cssxref("animation") }} скорочення є вигідним для економії місця. От, для прикладу, правила анімації, які ми вже використали в статті:

- -
p {
-  animation-duration: 3s;
-  animation-name: slidein;
-  animation-iteration-count: infinite;
-  animation-direction: alternate;
-}
-
- -

Їх можна замінити ось таким чином

- -
p {
-  animation: 3s infinite alternate slideIn;
-}
- -
-

Примітка: Ви можете дізнатися про це більше на сторінці довідки {{ cssxref("animation") }} :

-
- -

Задання множинних значень властивостей анімації

- -

Нескорочені значення CSS анімації можуть приймати множинні значення, розділені комами — таку особливість можна використати, якщо вам потрібно задати множинні анімації єдиним набором правил і відповідно задати різні тривалості, повтори і так далі для різних анімацій. Давайте глянемо на кілька швидких прикладів, аби пояснити різні зміни:

- -

В першому прикладі у нас є набір з трьох різних імен анімації, але одна й та ж тривалість і кількість повторів:

- -
animation-name: fadeInOut, moveLeft300px, bounce;
-animation-duration: 3s;
-animation-iteration-count: 1;
- -

В другому прикладі в нас є набір з 3х значень для кожної властивості. В цьому випадку кожна анімація буде здійснюватися з відповідними значеннями, згідно з їх розміщенням у властивостях, то ж, приміром, fadeInOut має тривалість в 2.5s і кількість повторів 2,  і т.д..

- -
animation-name: fadeInOut, moveLeft300px, bounce;
-animation-duration: 2.5s, 5s, 1s;
-animation-iteration-count: 2, 1, 5;
- -

У цьому третьому випадку є три різні анімації, але лише дві різні тривалості та кількості повторів. У таких випадках наборів значень недостатньо, то ж кожна анімація отримає свій набір значень шляхом перебору від початку до кінця. Наприклад, fadeInOut отримає тривалість в 2.5s і moveLeft300px матиме тривалість 5s. Набори значень на цьому закінчились, тому все починається з початку і третя анімація bounce отримає тривалість знову в 2.5s. Кількість повторів (та й будь-які інші значення властивостей, які ви задасте) будуть присвоєні такими самим чином.

- -
animation-name: fadeInOut, moveLeft300px, bounce;
-animation-duration: 2.5s, 5s;
-animation-iteration-count: 2, 1;
- -

Використання подій анімації

- -

Ви можете отримати додатковий контроль над анімаціями, як і корисну інформацію про них шляхом використання подій анімації. Ці події, представлені об'єктом {{ domxref("AnimationEvent") }}, можуть бути використані, аби визначити, коли починаються, закінчуються і починають новий повтор різні анімації. Кожна подія містить час, о котрій вона сталась та ім'я анімації, яка її запустила.

- -

Зараз ми змінимо приклад з ковзаючим текстом, аби вивести певну інформацію про кожну анімаційну подію, тобто її час, то ж ми можемо розібратися, як вони працюють.

- -

Додавання CSS

- -

Починаємо зі створення CSS для анімації. Дана анімація триватиме 3 секунди, назвемо її “slidein”, задамо повтор 3 рази, і напрям анімації alternate кожного разу. В {{ cssxref("@keyframes") }}, ширина і лівий маргін змінюються, щоб текст ковзав по екрану.

- -
.slidein {
-  animation-duration: 3s;
-  animation-name: slidein;
-  animation-iteration-count: 3;
-  animation-direction: alternate;
-}
-
-@keyframes slidein {
-  from {
-    margin-left:100%;
-    width:300%
-  }
-
-  to {
-    margin-left:0%;
-    width:100%;
-  }
-}
- -

Встановлення animation event listeners - прослуховування подій анімації

- -

Ми використаємо код JavaScript для прослуховування всіх трьох можливих подій анімації. Даний код задає наші event listeners; ми викликаємо його, коли документ вперше завантажений, для того, щоб отримати впорядковані дані.

- -
var e = document.getElementById("watchme");
-e.addEventListener("animationstart", listener, false);
-e.addEventListener("animationend", listener, false);
-e.addEventListener("animationiteration", listener, false);
-
-e.className = "slidein";
-
- -

Це цілком звичайний код, аби дізнатися більше, ви можете звіритися з документацією {{ domxref("eventTarget.addEventListener()") }}. Останнє, що робить код - він задає клас анімованого елемента як “slidein”; це нам потрібно для запуску анімації.

- -

Чому? Тому що подія animationstart запускається одразу ж, як стартує анімація; в даному випадку це стається до того, як починає діяти наш код. То ж ми починаємо анімацію самі, задаючи клас елементу для стиля, котрий буде анімований по факту.

- -

Отримання подій

- -

Події надсилаються до функції listener(), як це показано нижче.

- -
function listener(e) {
-  var l = document.createElement("li");
-  switch(e.type) {
-    case "animationstart":
-      l.innerHTML = "Started: elapsed time is " + e.elapsedTime;
-      break;
-    case "animationend":
-      l.innerHTML = "Ended: elapsed time is " + e.elapsedTime;
-      break;
-    case "animationiteration":
-      l.innerHTML = "New loop started at time " + e.elapsedTime;
-      break;
-  }
-  document.getElementById("output").appendChild(l);
-}
-
- -

Даний код також дуже простий. Він просто дивиться в {{ domxref("event.type") }}, аби визначити, який власне тип події анімації трапився, тоді додає відповідну примітку в {{ HTMLElement("ul") }} (невпорядкований список), який ми використовуємо для виводу звіту про ці події.

- -

Звіт після завершення роботи буде виглядати якось от так:

- - - -

Зауважте, що часи подій досить точні щодо тих, які ми очікували відповідно до таймінгу, який ми задали, коли створювали анімацію. Візьміть до уваги також і те, що після завершального проходу анімації подія animationiteration не була надіслана; натомість надіслало подію animationend.

- -

HTML

- -

Чисто для повної завершеності огляду ось код, який відображає контент сторіки, включно зі списком звіту про події анімації, який створився завдяки вищеописаному скрипту:

- -
<h1 id="watchme">Watch me move</h1>
-<p>
-  This example shows how to use CSS animations to make <code>H1</code>
-  elements move across the page.
-</p>
-<p>
-  In addition, we output some text each time an animation event fires,
-  so you can see them in action.
-</p>
-<ul id="output">
-</ul>
-</body>
-
- -

{{EmbedLiveSample('Using_animation_events', '600', '300')}}

- -

Дивіться також

- - diff --git a/files/uk/web/css/css_box_model/index.html b/files/uk/web/css/css_box_model/index.html new file mode 100644 index 0000000000..4920b7ceb9 --- /dev/null +++ b/files/uk/web/css/css_box_model/index.html @@ -0,0 +1,161 @@ +--- +title: Коробчаста модель CSS +slug: Web/CSS/Коробчаста_модель_CSS +tags: + - CSS + - Довідка + - Коробчаста модель CSS +translation_of: Web/CSS/CSS_Box_Model +--- +
Коробчаста модель (box model) — це алгоритм CSS, що подає елементи (включно з їх {{cssxref("margin", "відступами")}} та {{cssxref("padding", "полями")}}) у вигляді прямокутних «коробок» та компонує їх відповідно до {{cssxref("Visual_formatting_model", "моделі візуального формування")}}.
+ +

Довідка

+ +

Властивості

+ +

Властивості, що визначають потік (flow) вмісту

+ +
+ +
+ +

Властивості, що визначають розміри

+ +
+ +
+ +

Властивості, що визначають відступи

+ +
+ +
+ +

Властивості, що визначають поля

+ +
+ +
+ +

Інші властивості

+ +
+ +
+ +

Посібники

+ +
+
Вступ до коробчастої моделі CSS
+
Описує та пояснює одне з ґрунтовних понять в CSS — коробчасту модель. Ця модель визначає, як CSS розташовує елементи, їх вміст, {{cssxref("padding", "поля")}}, {{cssxref("border", "обрамок")}} та {{cssxref("margin", "відступи")}}.
+
Згортання відступів
+
Два прилеглі відступи інколи згортаються в один. Ця стаття наводить правила, за якими це відбувається, та пояснює, як цим керувати.
+
Модель візуального формування
+
Описує та пояснює модель візуального формування.
+
+ +

Специфікації

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
СпецифікаціяСтатусКоментар
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}} 
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Первинне визначення
+ +

Підтримка веб-переглядачами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
diff --git a/files/uk/web/css/css_box_model/mastering_margin_collapsing/index.html b/files/uk/web/css/css_box_model/mastering_margin_collapsing/index.html new file mode 100644 index 0000000000..b47325c5bf --- /dev/null +++ b/files/uk/web/css/css_box_model/mastering_margin_collapsing/index.html @@ -0,0 +1,90 @@ +--- +title: Згортання відступів +slug: Web/CSS/CSS_Box_Model/Згортання_відступів +tags: + - CSS + - Коробчаста модель CSS + - Посібник +translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +--- +
{{CSSRef}}
+ +

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.

+ +

Margin collapsing occurs in three basic cases:

+ +
+
Безпосередні (прилеглі) сусіди
+
The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats).
+
Батько та перший/останній дочірній елемент
+
If there is no border, padding, inline part, {{cssxref("Block_formatting_context")}} created, or clearance to separate the {{cssxref("margin-top")}} of a block from the {{cssxref("margin-top")}} of its first child block; or no border, padding, inline content, {{cssxref("height")}}, {{cssxref("min-height")}}, or {{cssxref("max-height")}} to separate the {{cssxref("margin-bottom")}} of a block from the {{cssxref("margin-bottom")}} of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
+
+ +
+
Порожні блоки
+
If there is no border, padding, inline content, {{cssxref("height")}}, or {{cssxref("min-height")}} to separate a block's {{cssxref("margin-top")}} from its {{cssxref("margin-bottom")}}, then its top and bottom margins collapse.
+
+ +

More complex margin collapsing (of more than two margins) occurs when these cases are combined.

+ +

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.

+ +

When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.

+ +

When all margins are negative, the size of the collapsed margin is the smallest (most negative) margin. This applies to both adjacent elements and nested elements.

+ +

Приклади

+ +

HTML

+ +
<p>The bottom margin of this paragraph is collapsed...</p>
+<p>...with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p>
+
+<div>This parent element contains two paragraphs!
+  <p>This paragraph has a <code>.4rem</code> margin between it and the text above.</p>
+  <p>My bottom margin collapses with my parent, yielding a bottom margin of <code>2rem</code>.</p>
+</div>
+
+<p>Blah blah blah.</p>
+ +

CSS

+ +
div {
+  margin: 2rem 0;
+  background: lavender;
+}
+
+p {
+  margin: .4rem 0 1.2rem 0;
+  background: yellow;
+}
+ +

Результат

+ +

{{EmbedLiveSample('Examples','100%',250)}}

+ +

Специфікації

+ + + + + + + + + + + + + + + + +
СпецифікаціяСтатусКоментар
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}}{{Spec2("CSS2.1")}}Первинне визначення
+ +

Див. також

+ + diff --git "a/files/uk/web/css/css_box_model/\320\267\320\263\320\276\321\200\321\202\320\260\320\275\320\275\321\217_\320\262\321\226\320\264\321\201\321\202\321\203\320\277\321\226\320\262/index.html" "b/files/uk/web/css/css_box_model/\320\267\320\263\320\276\321\200\321\202\320\260\320\275\320\275\321\217_\320\262\321\226\320\264\321\201\321\202\321\203\320\277\321\226\320\262/index.html" deleted file mode 100644 index b47325c5bf..0000000000 --- "a/files/uk/web/css/css_box_model/\320\267\320\263\320\276\321\200\321\202\320\260\320\275\320\275\321\217_\320\262\321\226\320\264\321\201\321\202\321\203\320\277\321\226\320\262/index.html" +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Згортання відступів -slug: Web/CSS/CSS_Box_Model/Згортання_відступів -tags: - - CSS - - Коробчаста модель CSS - - Посібник -translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing ---- -
{{CSSRef}}
- -

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.

- -

Margin collapsing occurs in three basic cases:

- -
-
Безпосередні (прилеглі) сусіди
-
The margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats).
-
Батько та перший/останній дочірній елемент
-
If there is no border, padding, inline part, {{cssxref("Block_formatting_context")}} created, or clearance to separate the {{cssxref("margin-top")}} of a block from the {{cssxref("margin-top")}} of its first child block; or no border, padding, inline content, {{cssxref("height")}}, {{cssxref("min-height")}}, or {{cssxref("max-height")}} to separate the {{cssxref("margin-bottom")}} of a block from the {{cssxref("margin-bottom")}} of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
-
- -
-
Порожні блоки
-
If there is no border, padding, inline content, {{cssxref("height")}}, or {{cssxref("min-height")}} to separate a block's {{cssxref("margin-top")}} from its {{cssxref("margin-bottom")}}, then its top and bottom margins collapse.
-
- -

More complex margin collapsing (of more than two margins) occurs when these cases are combined.

- -

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.

- -

When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.

- -

When all margins are negative, the size of the collapsed margin is the smallest (most negative) margin. This applies to both adjacent elements and nested elements.

- -

Приклади

- -

HTML

- -
<p>The bottom margin of this paragraph is collapsed...</p>
-<p>...with the top margin of this paragraph, yielding a margin of <code>1.2rem</code> in between.</p>
-
-<div>This parent element contains two paragraphs!
-  <p>This paragraph has a <code>.4rem</code> margin between it and the text above.</p>
-  <p>My bottom margin collapses with my parent, yielding a bottom margin of <code>2rem</code>.</p>
-</div>
-
-<p>Blah blah blah.</p>
- -

CSS

- -
div {
-  margin: 2rem 0;
-  background: lavender;
-}
-
-p {
-  margin: .4rem 0 1.2rem 0;
-  background: yellow;
-}
- -

Результат

- -

{{EmbedLiveSample('Examples','100%',250)}}

- -

Специфікації

- - - - - - - - - - - - - - - - -
СпецифікаціяСтатусКоментар
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}}{{Spec2("CSS2.1")}}Первинне визначення
- -

Див. також

- - diff --git a/files/uk/web/css/css_flexible_box_layout/basic_concepts_of_flexbox/index.html b/files/uk/web/css/css_flexible_box_layout/basic_concepts_of_flexbox/index.html new file mode 100644 index 0000000000..e111a70633 --- /dev/null +++ b/files/uk/web/css/css_flexible_box_layout/basic_concepts_of_flexbox/index.html @@ -0,0 +1,391 @@ +--- +title: Використання CSS flexible-боксів +slug: Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox +translation_of_original: Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes +--- +
{{CSSRef}}
+ +

CSS3 flex-бокс, або flexbox, це режим розмітки створений для упорядкування елементів на сторінці таким чином, щоб вони поводилися передбачувано у випадках, коли розмітка сторінки адаптована під різні розміри екрану і різні девайси.  В багатьох випадках flexible box є вдосконаленням блокової моделі розмітки, яка не використовує обтікання (floats) і не виконує схлопування відступів flex контейнера і  його контенту (margins collapse).

+ +

Для багатьох дизайнерів модель використання flex-боксів буде більш простою для застосування. Дочірні елементи всередині flex-боксу можуть розміщуватись у будь-якому напрямку і можуть мати змінні виміри щоб адаптовуватись до різних розмірів дисплею. Позиціонування елементів у такому разі є простішим і комплексна розмітка досягається значно легше і з чистішим кодом, оскільки порядок відображення елементів не пов'язаний із їх порядком в коді. Ця незалежність навмисне стосується лише візуального рендерингу, залишаючи порядок інтерпритації і навігацію залежними від порядку у сорсі.

+ +
Увага: Де-які броузери все ще можуть частково або повністю не підтримувати flex боксів. Ознайомтесь із  таблицею сумісності для flex боксів
+ +

Концепція flex-боксів

+ +

Головною концепцією flex-боксів є можливість зміни висоти та/або ширини його елементів шоб найкраше заповнювати простір будь-якого дисплею. Flex-контейнер збільшує елементи, щоб заповнити доступний простір чи зменшує щоб запобігти перекриванню.

+ +

Алгоритм розмітки flex-боксами є напрямно-агностичним на противагу блоковій розмітці, яка вертикально-орієнтована, чи горизонтально-орієнтованій інлайн-розмітці. Не зважаючи на те що розмітка блоками добре підходить для сторінки, їй не вистачає об'єктивного механізму для підтримки компонентів, що повинні змінювати орієнтацію, розміри а також розтягуватись чи стискатись при змінах юзер-агента, змінах з вертикальної на горизонтальну орієнтацію і таке інше. Розмітка flex-боксами найбільш бажана для компонентів додатку і шаблонів, що мало масштабуються, тоді як grid-розмітка створена для великих шаблонів, що масштабуються. Обидві технології є частиною розробки CSS Working Group яка має сприяти сумісності web-аплікацій з різними юзер-агентами, режимами а також більшій гнучкості.

+ +

Словник Flexible box термінів  

+ +

Оскільки опис flexible-боксів не включає таких словосполучень, як горизонтальна/інлайн і вертикальна/блокова осі, пояснення моделі передбачає нову термінологію. Використовуйте наступну діаграму під час перегляду словника термінів. Вона зображає flex-контейнер, що має  flex-напрямок ряду, що означає, що кожен flex item розміщений горизонтально, один за одним по головній осі (main axis) відповідно до встановленного режиму написання, напрямку тексту елементу. Зліва-направо у данному випадку.

+ +

flex_terms.png

+ +
+
Flex-контейнер
+
Батьківський елемент, у якому містяться flex-айтеми. Flex-контейнер визначається flex або inline-flex значеннями {{Cssxref("display")}} властивості.
+
Flex-айтем
+
+

Кожен дочірній елемент flex-контейнеру стає flex-айтемом. Текст, що напряму міститься в flex-контейнері обгортається анонімним flex-айтемом.

+
+
Осі
+
+

Кожен flexible-бокс шаблон будується по двох осях. Головна вісь (main axis) - вісь, вздовж якої flex-айтеми слідують один за одним. Перехресна вісь (cross axis) вісь, що перпендикулярна до main axis.

+ +
    +
  • Властивість flex-direction встановлює main axis.
  • +
  • Властивість justify-content визначає як flex-айтеми розташовані вздовж main axis на поточній лінії.
  • +
  • Властивість align-items визначає замовчування для розташування flex-айтемів вздовж cross axis на поточній лінії.
  • +
  • Властивість align-self встановлює, як кожен окремий flex-айтем вирівняний по cross axis і переписує замовчування, встановлене за допомогою align-items.
  • +
+
+
Напрямки
+
+

Головний початок/головний кінець(main start/main end) і перехресний початок/перехресний кінець(cross start/cross end) це сторони flex-контейнера, що визначають початок і закінчення потоку flex-айтемів. Вони слідують за головною і перехресною осями flex-контейнера у векторі, встановленому режимом написання (зліва-направо, зправа-наліво і т.д.).

+ +
    +
  • Властивість order присвоює елементи порядковим групам і визначає, який елемент є першим.
  • +
  • Властивість flex-flow це скорочена форма для flex-direction та flex-wrap властивостей.
  • +
+
+
Лінії
+
+

Flex-айтеми можуть бути розміщені на одній чи кількох лініях відповідно до flex-wrap властивості, яка контролює напрямок перехресних ліній і напрямок у якому складаються нові лінії.

+
+
Виміри
+
Еквівалентами для height і width для flex-айтемів є main size та cross size, які відповідно стосуються main axis і cross axis flex-контейнера.
+
+
    +
  • Початковим значенням для min-height і min-width є 0.
  • +
  • Властивість flex виступає скороченням для flex-grow, flex-shrink, а також flex-basis властивостей для встановлення гнучкості flex-айтема.
  • +
+
+
+ +

Робимо елемент flexible-боксом

+ +

Щоб зробити елемент flexible-боксом, вкажіт занчення display властивості наступним чином:

+ +
display : flex
+ +

або

+ +
display : inline-flex
+ +

Роблячи таким чином, ми визначаєм елемент як flexible-бокс, а його нащадків- як flexible-айтеми. Значення flex робить контейнер блоковим елементом. А inline-flex значення перетворює його на інлайн-елемент.

+ +
Увага: Для вказання префіксу вендора, додайте рядок до значення атрибуту, а не до самого атрибуту. Наприклад, display : -webkit-flex.
+ +

Характеристики flex-айтема

+ +

Текст, що напряму поміщений до flex-контейнера автоматично обгортається в анонімний flex-айтем. Тим не менше анонімний flex-айтем, що містить лише пробільні симфоли не рендериться, так ніби йому було встановлене правило display: none.

+ +

Абсолютно-позиціоновані дочірні елементи flex-контейнера позиціонуються так, що іхня статична позиція визначається відносно головного стартового кута контент-боксу їхнього flex-контейнера.

+ +

У сусідніх flex-айтемів марджіни не накладаються один на інший. Використовуючи auto марджіни можна поглинути зайві відстані у вертикальному чи горизонтальному напрямках тим самим досягнувши вирівнювання чи розмежування сусідніх flex-айтемів.  Для детальної інформації прочитайте  вирівнювання з допомогою 'auto' марджінів у W3C специфікації "модель Flexible-бокс розмітки" (англ.).

+ +

Для забезпечення адекватного замовчування мінімальних розмірів flex-айтема, використовуйте min-width:auto і/або min-height:auto. Для flex-айтемів, значення атрибуту auto вираховує мінімальну ширину/висоту айтема щоб не були меншими за ширину/висоту їхнього контенту, гарантуючи, що айтем відрендерений достатньо великим, для того, щоб вмістити контент. Дивіться {{cssxref("min-width")}} і {{cssxref("min-height")}} для більш детальної інформації.

+ +

Атрибути вирівнювання flex-боксів виконують справжнє центрування, на відміну від інших методів центрування у CSS. Це означає, що flex-айтеми залишаться відцентрованими навіть коли вони виходять за межі flex-контейнера. Хоча така ситуація де-коли можи бути проблемою, оскільки якщо вони виходять за межі верхнього чи лівого (для LTR мов , таких, як англійська чи українська; проблема актуальна для правого краю для RTL мов, таких, як арабська) країв сторінки, вам не вдасться проскролити до цієї частини, не зважаючи на те, що там є контент! В майбутньому релізі властивості вирівнювання мають бути розширені для підтримаки безпечного режиму також. Зараз, якщо це проблема, Ви можете використовувати відступи (margin), щоб досягнути центрування.

+ +

For now, if this is a concern, you can instead use margins to achieve centering, as they'll respond in a "safe" way and stop centering if they overflow. Instead of using the align- properties, just put auto margins on the flex items you wish to center. Instead of the justify- properties, put auto margins on the outside edges of the first and last flex items in the flex container. The auto margins will "flex" and assume the leftover space, centering the flex items when there is leftover space, and switching to normal alignment when not. However, if you're trying to replace justify-content with margin-based centering in a multi-line flexbox, you're probably out of luck, as you need to put the margins on the first and last flex item on each line. Unless you can predict ahead of time which items will end up on which line, you can't reliably use margin-based centering in the main axis to replace the justify-content property.

+ +

Recall that while the display order of the elements is independent of their order in the source code, this independence affects only the visual rendering, leaving speech order and navigation based on the source order. Even the {{cssxref("order")}} property does not affect speech or navigation sequence. Thus developers must take care to order elements properly in the source so as not to damage the document's accessibility.

+ +

Flexible box properties

+ +

Properties not affecting flexible boxes

+ +

Because flexible boxes use a different layout algorithm, some properties do not make sense on a flex container:

+ + + +

Examples

+ +

Basic flex example

+ +

This basic example shows how to apply "flexibility" to an element and how sibling elements behave in a flexible state.

+ +
​<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <style>
+
+   .flex
+   {
+      /* basic styling */
+      width: 350px;
+      height: 200px;
+      border: 1px solid #555;
+      font: 14px Arial;
+
+      /* flexbox setup */
+      display: -webkit-flex;
+      -webkit-flex-direction: row;
+
+      display: flex;
+      flex-direction: row;
+   }
+
+   .flex > div
+   {
+      -webkit-flex: 1 1 auto;
+      flex: 1 1 auto;
+
+      width: 30px; /* To make the transition work nicely.  (Transitions to/from
+                      "width:auto" are buggy in Gecko and Webkit, at least.
+                      See http://bugzil.la/731886 for more info.) */
+
+      -webkit-transition: width 0.7s ease-out;
+      transition: width 0.7s ease-out;
+   }
+
+   /* colors */
+   .flex > div:nth-child(1){ background : #009246; }
+   .flex > div:nth-child(2){ background : #F1F2F1; }
+   .flex > div:nth-child(3){ background : #CE2B37; }
+
+   .flex > div:hover
+   {
+        width: 200px;
+   }
+
+   </style>
+
+ </head>
+ <body>
+  <p>Flexbox nuovo</p>
+  <div class="flex">
+    <div>uno</div>
+    <div>due</div>
+    <div>tre</div>
+  </div>
+ </body>
+</html>
+ +

Holy Grail Layout example

+ +

This example demonstrates how flexbox provides the ability to dynamically change the layout for different screen resolutions. The following diagram illustrates the transformation.

+ +

HolyGrailLayout.png

+ +

Illustrated here is the case where the page layout suited to a browser window must be optimized for a smart phone window. Not only must the elements reduce in size, but the order in which they are presented must change. Flexbox makes this very simple.

+ +
​<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <style>
+
+  body {
+   font: 24px Helvetica;
+   background: #999999;
+  }
+
+  #main {
+   min-height: 800px;
+   margin: 0px;
+   padding: 0px;
+   display: -webkit-flex;
+   display:         flex;
+   -webkit-flex-flow: row;
+           flex-flow: row;
+   }
+
+  #main > article {
+   margin: 4px;
+   padding: 5px;
+   border: 1px solid #cccc33;
+   border-radius: 7pt;
+   background: #dddd88;
+   -webkit-flex: 3 1 60%;
+           flex: 3 1 60%;
+   -webkit-order: 2;
+           order: 2;
+   }
+
+  #main > nav {
+   margin: 4px;
+   padding: 5px;
+   border: 1px solid #8888bb;
+   border-radius: 7pt;
+   background: #ccccff;
+   -webkit-flex: 1 6 20%;
+           flex: 1 6 20%;
+   -webkit-order: 1;
+           order: 1;
+   }
+
+  #main > aside {
+   margin: 4px;
+   padding: 5px;
+   border: 1px solid #8888bb;
+   border-radius: 7pt;
+   background: #ccccff;
+   -webkit-flex: 1 6 20%;
+           flex: 1 6 20%;
+   -webkit-order: 3;
+           order: 3;
+   }
+
+  header, footer {
+   display: block;
+   margin: 4px;
+   padding: 5px;
+   min-height: 100px;
+   border: 1px solid #eebb55;
+   border-radius: 7pt;
+   background: #ffeebb;
+   }
+
+  /* Too narrow to support three columns */
+  @media all and (max-width: 640px) {
+
+   #main, #page {
+    -webkit-flex-flow: column;
+            flex-direction: column;
+   }
+
+   #main > article, #main > nav, #main > aside {
+    /* Return them to document order */
+    -webkit-order: 0;
+            order: 0;
+   }
+
+   #main > nav, #main > aside, header, footer {
+    min-height: 50px;
+    max-height: 50px;
+   }
+  }
+
+ </style>
+  </head>
+  <body>
+ <header>header</header>
+ <div id='main'>
+    <article>article</article>
+    <nav>nav</nav>
+    <aside>aside</aside>
+ </div>
+ <footer>footer</footer>
+  </body>
+</html>
+ +

Playground

+ +

There are a few flexbox playgrounds available online for experimenting:

+ + + +

Things to keep in mind

+ +

The algorithm describing how flex items are laid out can be pretty tricky at times. Here are a few things to consider to avoid bad surprises when designing using flexible boxes.

+ +

Flexible boxes are laid out in conformance of the writing mode, which means that main start and main end are laid out according to the position of start and end.

+ +

cross start and cross end rely on the definition of the start or before position that depends on the value of direction.

+ +

Page breaks are possible in flexible boxes layout as long as break- property allows it. CSS3 break-after, break-before, and break-inside as well as CSS 2.1 page-break-before, page-break-after, and page-break-inside properties are accepted on a flex container, flex items, and inside flex items.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support (single-line flexbox){{CompatGeckoDesktop("18.0")}}[6]{{property_prefix("-moz")}}[2]
+ {{CompatGeckoDesktop("22.0")}}
21.0{{property_prefix("-webkit")}}
+ 29.0
11[3]12.10{{property_prefix("-webkit")}}[5]6.1{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoDesktop("28.0")}}21.0{{property_prefix("-webkit")}}
+ 29.0
11[3]12.10[5]
+ 15 {{property_prefix("-webkit")}}
6.1{{property_prefix("-webkit")}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)Firefox OSAndroidIE PhoneOpera MobileSafari Mobile
Basic support (single-line flexbox){{CompatGeckoMobile("18.0")}}{{property_prefix("-moz")}}[2]
+ {{CompatGeckoMobile("22.0")}}
+

1.0{{property_prefix("-moz")}}[2]
+ 1.1

+
2.1{{property_prefix("-webkit")}}[4]
+ 4.4
1112.10[5]
+ 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoMobile("28.0")}}1.32.1{{property_prefix("-webkit")}}[4]
+ 4.4
1112.10[5]
+ 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
+
+ +

[1] Safari up to version  6.0 (iOS.1) supported an old incompatible draft version of the specification. Safari 6.1 (and Safari on iOS 7) has been updated to support the final version.

+ +

[2] Up to Firefox 22, to activate flexbox support, the user has to change the about:config preference layout.css.flexbox.enabled to true. From Firefox 22 to Firefox 27, the preference is true by default, but the preference has been removed in Firefox 28.

+ +

[3] Internet Explorer 10 supports an old incompatible draft version of the specification; Internet Explorer 11 has been updated to support the final version.

+ +

[4] Android browser up to 4.3 supported an old incompatible draft version of the specification. Android 4.4 has been updated to support the final version.

+ +

[5] While in the initial implementation in Opera 12.10 flexbox was not prefixed, it got prefixed in versions 15 to 16 of Opera and 15 to 19 of Opera Mobile with {{property_prefix("-webkit")}}. The prefix was removed again in Opera 17 and Opera Mobile 24.

+ +

[6] Up to Firefox 29, specifying visibility: collapse on a flex item causes it to be treated as if it were display: none instead of the intended behavior, treating it as if it were visibility: hidden. The suggested workaround is to use visibility:hidden for flex items that should behave as if they were designated visibility:collapse. For more information, see {{bug(783470)}}

diff --git a/files/uk/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html b/files/uk/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html deleted file mode 100644 index e111a70633..0000000000 --- a/files/uk/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html +++ /dev/null @@ -1,391 +0,0 @@ ---- -title: Використання CSS flexible-боксів -slug: Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes -translation_of: Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox -translation_of_original: Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes ---- -
{{CSSRef}}
- -

CSS3 flex-бокс, або flexbox, це режим розмітки створений для упорядкування елементів на сторінці таким чином, щоб вони поводилися передбачувано у випадках, коли розмітка сторінки адаптована під різні розміри екрану і різні девайси.  В багатьох випадках flexible box є вдосконаленням блокової моделі розмітки, яка не використовує обтікання (floats) і не виконує схлопування відступів flex контейнера і  його контенту (margins collapse).

- -

Для багатьох дизайнерів модель використання flex-боксів буде більш простою для застосування. Дочірні елементи всередині flex-боксу можуть розміщуватись у будь-якому напрямку і можуть мати змінні виміри щоб адаптовуватись до різних розмірів дисплею. Позиціонування елементів у такому разі є простішим і комплексна розмітка досягається значно легше і з чистішим кодом, оскільки порядок відображення елементів не пов'язаний із їх порядком в коді. Ця незалежність навмисне стосується лише візуального рендерингу, залишаючи порядок інтерпритації і навігацію залежними від порядку у сорсі.

- -
Увага: Де-які броузери все ще можуть частково або повністю не підтримувати flex боксів. Ознайомтесь із  таблицею сумісності для flex боксів
- -

Концепція flex-боксів

- -

Головною концепцією flex-боксів є можливість зміни висоти та/або ширини його елементів шоб найкраше заповнювати простір будь-якого дисплею. Flex-контейнер збільшує елементи, щоб заповнити доступний простір чи зменшує щоб запобігти перекриванню.

- -

Алгоритм розмітки flex-боксами є напрямно-агностичним на противагу блоковій розмітці, яка вертикально-орієнтована, чи горизонтально-орієнтованій інлайн-розмітці. Не зважаючи на те що розмітка блоками добре підходить для сторінки, їй не вистачає об'єктивного механізму для підтримки компонентів, що повинні змінювати орієнтацію, розміри а також розтягуватись чи стискатись при змінах юзер-агента, змінах з вертикальної на горизонтальну орієнтацію і таке інше. Розмітка flex-боксами найбільш бажана для компонентів додатку і шаблонів, що мало масштабуються, тоді як grid-розмітка створена для великих шаблонів, що масштабуються. Обидві технології є частиною розробки CSS Working Group яка має сприяти сумісності web-аплікацій з різними юзер-агентами, режимами а також більшій гнучкості.

- -

Словник Flexible box термінів  

- -

Оскільки опис flexible-боксів не включає таких словосполучень, як горизонтальна/інлайн і вертикальна/блокова осі, пояснення моделі передбачає нову термінологію. Використовуйте наступну діаграму під час перегляду словника термінів. Вона зображає flex-контейнер, що має  flex-напрямок ряду, що означає, що кожен flex item розміщений горизонтально, один за одним по головній осі (main axis) відповідно до встановленного режиму написання, напрямку тексту елементу. Зліва-направо у данному випадку.

- -

flex_terms.png

- -
-
Flex-контейнер
-
Батьківський елемент, у якому містяться flex-айтеми. Flex-контейнер визначається flex або inline-flex значеннями {{Cssxref("display")}} властивості.
-
Flex-айтем
-
-

Кожен дочірній елемент flex-контейнеру стає flex-айтемом. Текст, що напряму міститься в flex-контейнері обгортається анонімним flex-айтемом.

-
-
Осі
-
-

Кожен flexible-бокс шаблон будується по двох осях. Головна вісь (main axis) - вісь, вздовж якої flex-айтеми слідують один за одним. Перехресна вісь (cross axis) вісь, що перпендикулярна до main axis.

- -
    -
  • Властивість flex-direction встановлює main axis.
  • -
  • Властивість justify-content визначає як flex-айтеми розташовані вздовж main axis на поточній лінії.
  • -
  • Властивість align-items визначає замовчування для розташування flex-айтемів вздовж cross axis на поточній лінії.
  • -
  • Властивість align-self встановлює, як кожен окремий flex-айтем вирівняний по cross axis і переписує замовчування, встановлене за допомогою align-items.
  • -
-
-
Напрямки
-
-

Головний початок/головний кінець(main start/main end) і перехресний початок/перехресний кінець(cross start/cross end) це сторони flex-контейнера, що визначають початок і закінчення потоку flex-айтемів. Вони слідують за головною і перехресною осями flex-контейнера у векторі, встановленому режимом написання (зліва-направо, зправа-наліво і т.д.).

- -
    -
  • Властивість order присвоює елементи порядковим групам і визначає, який елемент є першим.
  • -
  • Властивість flex-flow це скорочена форма для flex-direction та flex-wrap властивостей.
  • -
-
-
Лінії
-
-

Flex-айтеми можуть бути розміщені на одній чи кількох лініях відповідно до flex-wrap властивості, яка контролює напрямок перехресних ліній і напрямок у якому складаються нові лінії.

-
-
Виміри
-
Еквівалентами для height і width для flex-айтемів є main size та cross size, які відповідно стосуються main axis і cross axis flex-контейнера.
-
-
    -
  • Початковим значенням для min-height і min-width є 0.
  • -
  • Властивість flex виступає скороченням для flex-grow, flex-shrink, а також flex-basis властивостей для встановлення гнучкості flex-айтема.
  • -
-
-
- -

Робимо елемент flexible-боксом

- -

Щоб зробити елемент flexible-боксом, вкажіт занчення display властивості наступним чином:

- -
display : flex
- -

або

- -
display : inline-flex
- -

Роблячи таким чином, ми визначаєм елемент як flexible-бокс, а його нащадків- як flexible-айтеми. Значення flex робить контейнер блоковим елементом. А inline-flex значення перетворює його на інлайн-елемент.

- -
Увага: Для вказання префіксу вендора, додайте рядок до значення атрибуту, а не до самого атрибуту. Наприклад, display : -webkit-flex.
- -

Характеристики flex-айтема

- -

Текст, що напряму поміщений до flex-контейнера автоматично обгортається в анонімний flex-айтем. Тим не менше анонімний flex-айтем, що містить лише пробільні симфоли не рендериться, так ніби йому було встановлене правило display: none.

- -

Абсолютно-позиціоновані дочірні елементи flex-контейнера позиціонуються так, що іхня статична позиція визначається відносно головного стартового кута контент-боксу їхнього flex-контейнера.

- -

У сусідніх flex-айтемів марджіни не накладаються один на інший. Використовуючи auto марджіни можна поглинути зайві відстані у вертикальному чи горизонтальному напрямках тим самим досягнувши вирівнювання чи розмежування сусідніх flex-айтемів.  Для детальної інформації прочитайте  вирівнювання з допомогою 'auto' марджінів у W3C специфікації "модель Flexible-бокс розмітки" (англ.).

- -

Для забезпечення адекватного замовчування мінімальних розмірів flex-айтема, використовуйте min-width:auto і/або min-height:auto. Для flex-айтемів, значення атрибуту auto вираховує мінімальну ширину/висоту айтема щоб не були меншими за ширину/висоту їхнього контенту, гарантуючи, що айтем відрендерений достатньо великим, для того, щоб вмістити контент. Дивіться {{cssxref("min-width")}} і {{cssxref("min-height")}} для більш детальної інформації.

- -

Атрибути вирівнювання flex-боксів виконують справжнє центрування, на відміну від інших методів центрування у CSS. Це означає, що flex-айтеми залишаться відцентрованими навіть коли вони виходять за межі flex-контейнера. Хоча така ситуація де-коли можи бути проблемою, оскільки якщо вони виходять за межі верхнього чи лівого (для LTR мов , таких, як англійська чи українська; проблема актуальна для правого краю для RTL мов, таких, як арабська) країв сторінки, вам не вдасться проскролити до цієї частини, не зважаючи на те, що там є контент! В майбутньому релізі властивості вирівнювання мають бути розширені для підтримаки безпечного режиму також. Зараз, якщо це проблема, Ви можете використовувати відступи (margin), щоб досягнути центрування.

- -

For now, if this is a concern, you can instead use margins to achieve centering, as they'll respond in a "safe" way and stop centering if they overflow. Instead of using the align- properties, just put auto margins on the flex items you wish to center. Instead of the justify- properties, put auto margins on the outside edges of the first and last flex items in the flex container. The auto margins will "flex" and assume the leftover space, centering the flex items when there is leftover space, and switching to normal alignment when not. However, if you're trying to replace justify-content with margin-based centering in a multi-line flexbox, you're probably out of luck, as you need to put the margins on the first and last flex item on each line. Unless you can predict ahead of time which items will end up on which line, you can't reliably use margin-based centering in the main axis to replace the justify-content property.

- -

Recall that while the display order of the elements is independent of their order in the source code, this independence affects only the visual rendering, leaving speech order and navigation based on the source order. Even the {{cssxref("order")}} property does not affect speech or navigation sequence. Thus developers must take care to order elements properly in the source so as not to damage the document's accessibility.

- -

Flexible box properties

- -

Properties not affecting flexible boxes

- -

Because flexible boxes use a different layout algorithm, some properties do not make sense on a flex container:

- - - -

Examples

- -

Basic flex example

- -

This basic example shows how to apply "flexibility" to an element and how sibling elements behave in a flexible state.

- -
​<!DOCTYPE html>
-<html lang="en">
-  <head>
-    <style>
-
-   .flex
-   {
-      /* basic styling */
-      width: 350px;
-      height: 200px;
-      border: 1px solid #555;
-      font: 14px Arial;
-
-      /* flexbox setup */
-      display: -webkit-flex;
-      -webkit-flex-direction: row;
-
-      display: flex;
-      flex-direction: row;
-   }
-
-   .flex > div
-   {
-      -webkit-flex: 1 1 auto;
-      flex: 1 1 auto;
-
-      width: 30px; /* To make the transition work nicely.  (Transitions to/from
-                      "width:auto" are buggy in Gecko and Webkit, at least.
-                      See http://bugzil.la/731886 for more info.) */
-
-      -webkit-transition: width 0.7s ease-out;
-      transition: width 0.7s ease-out;
-   }
-
-   /* colors */
-   .flex > div:nth-child(1){ background : #009246; }
-   .flex > div:nth-child(2){ background : #F1F2F1; }
-   .flex > div:nth-child(3){ background : #CE2B37; }
-
-   .flex > div:hover
-   {
-        width: 200px;
-   }
-
-   </style>
-
- </head>
- <body>
-  <p>Flexbox nuovo</p>
-  <div class="flex">
-    <div>uno</div>
-    <div>due</div>
-    <div>tre</div>
-  </div>
- </body>
-</html>
- -

Holy Grail Layout example

- -

This example demonstrates how flexbox provides the ability to dynamically change the layout for different screen resolutions. The following diagram illustrates the transformation.

- -

HolyGrailLayout.png

- -

Illustrated here is the case where the page layout suited to a browser window must be optimized for a smart phone window. Not only must the elements reduce in size, but the order in which they are presented must change. Flexbox makes this very simple.

- -
​<!DOCTYPE html>
-<html lang="en">
-  <head>
-    <style>
-
-  body {
-   font: 24px Helvetica;
-   background: #999999;
-  }
-
-  #main {
-   min-height: 800px;
-   margin: 0px;
-   padding: 0px;
-   display: -webkit-flex;
-   display:         flex;
-   -webkit-flex-flow: row;
-           flex-flow: row;
-   }
-
-  #main > article {
-   margin: 4px;
-   padding: 5px;
-   border: 1px solid #cccc33;
-   border-radius: 7pt;
-   background: #dddd88;
-   -webkit-flex: 3 1 60%;
-           flex: 3 1 60%;
-   -webkit-order: 2;
-           order: 2;
-   }
-
-  #main > nav {
-   margin: 4px;
-   padding: 5px;
-   border: 1px solid #8888bb;
-   border-radius: 7pt;
-   background: #ccccff;
-   -webkit-flex: 1 6 20%;
-           flex: 1 6 20%;
-   -webkit-order: 1;
-           order: 1;
-   }
-
-  #main > aside {
-   margin: 4px;
-   padding: 5px;
-   border: 1px solid #8888bb;
-   border-radius: 7pt;
-   background: #ccccff;
-   -webkit-flex: 1 6 20%;
-           flex: 1 6 20%;
-   -webkit-order: 3;
-           order: 3;
-   }
-
-  header, footer {
-   display: block;
-   margin: 4px;
-   padding: 5px;
-   min-height: 100px;
-   border: 1px solid #eebb55;
-   border-radius: 7pt;
-   background: #ffeebb;
-   }
-
-  /* Too narrow to support three columns */
-  @media all and (max-width: 640px) {
-
-   #main, #page {
-    -webkit-flex-flow: column;
-            flex-direction: column;
-   }
-
-   #main > article, #main > nav, #main > aside {
-    /* Return them to document order */
-    -webkit-order: 0;
-            order: 0;
-   }
-
-   #main > nav, #main > aside, header, footer {
-    min-height: 50px;
-    max-height: 50px;
-   }
-  }
-
- </style>
-  </head>
-  <body>
- <header>header</header>
- <div id='main'>
-    <article>article</article>
-    <nav>nav</nav>
-    <aside>aside</aside>
- </div>
- <footer>footer</footer>
-  </body>
-</html>
- -

Playground

- -

There are a few flexbox playgrounds available online for experimenting:

- - - -

Things to keep in mind

- -

The algorithm describing how flex items are laid out can be pretty tricky at times. Here are a few things to consider to avoid bad surprises when designing using flexible boxes.

- -

Flexible boxes are laid out in conformance of the writing mode, which means that main start and main end are laid out according to the position of start and end.

- -

cross start and cross end rely on the definition of the start or before position that depends on the value of direction.

- -

Page breaks are possible in flexible boxes layout as long as break- property allows it. CSS3 break-after, break-before, and break-inside as well as CSS 2.1 page-break-before, page-break-after, and page-break-inside properties are accepted on a flex container, flex items, and inside flex items.

- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support (single-line flexbox){{CompatGeckoDesktop("18.0")}}[6]{{property_prefix("-moz")}}[2]
- {{CompatGeckoDesktop("22.0")}}
21.0{{property_prefix("-webkit")}}
- 29.0
11[3]12.10{{property_prefix("-webkit")}}[5]6.1{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoDesktop("28.0")}}21.0{{property_prefix("-webkit")}}
- 29.0
11[3]12.10[5]
- 15 {{property_prefix("-webkit")}}
6.1{{property_prefix("-webkit")}}[1]
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)Firefox OSAndroidIE PhoneOpera MobileSafari Mobile
Basic support (single-line flexbox){{CompatGeckoMobile("18.0")}}{{property_prefix("-moz")}}[2]
- {{CompatGeckoMobile("22.0")}}
-

1.0{{property_prefix("-moz")}}[2]
- 1.1

-
2.1{{property_prefix("-webkit")}}[4]
- 4.4
1112.10[5]
- 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoMobile("28.0")}}1.32.1{{property_prefix("-webkit")}}[4]
- 4.4
1112.10[5]
- 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
-
- -

[1] Safari up to version  6.0 (iOS.1) supported an old incompatible draft version of the specification. Safari 6.1 (and Safari on iOS 7) has been updated to support the final version.

- -

[2] Up to Firefox 22, to activate flexbox support, the user has to change the about:config preference layout.css.flexbox.enabled to true. From Firefox 22 to Firefox 27, the preference is true by default, but the preference has been removed in Firefox 28.

- -

[3] Internet Explorer 10 supports an old incompatible draft version of the specification; Internet Explorer 11 has been updated to support the final version.

- -

[4] Android browser up to 4.3 supported an old incompatible draft version of the specification. Android 4.4 has been updated to support the final version.

- -

[5] While in the initial implementation in Opera 12.10 flexbox was not prefixed, it got prefixed in versions 15 to 16 of Opera and 15 to 19 of Opera Mobile with {{property_prefix("-webkit")}}. The prefix was removed again in Opera 17 and Opera Mobile 24.

- -

[6] Up to Firefox 29, specifying visibility: collapse on a flex item causes it to be treated as if it were display: none instead of the intended behavior, treating it as if it were visibility: hidden. The suggested workaround is to use visibility:hidden for flex items that should behave as if they were designated visibility:collapse. For more information, see {{bug(783470)}}

diff --git a/files/uk/web/css/layout_cookbook/index.html b/files/uk/web/css/layout_cookbook/index.html new file mode 100644 index 0000000000..e6d7f61135 --- /dev/null +++ b/files/uk/web/css/layout_cookbook/index.html @@ -0,0 +1,80 @@ +--- +title: Кулінарна книга з CSS розмітки +slug: Web/CSS/Розмітка_кулінарна-книга +translation_of: Web/CSS/Layout_cookbook +--- +
{{CSSRef}}
+ +

The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.

+ +
+

Note: If you are new to CSS layout then you might first like to take a look at our CSS layout learning module, as this will give you the basic grounding you need to make use of the recipes here.

+
+ +

The Recipes

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecipeDescriptionLayout Methods
Media objectsA two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet.CSS Grid, {{cssxref("float")}} fallback, {{cssxref("fit-content")}} sizing
ColumnsWhen to choose multi-column layout, flexbox or grid for your columns.CSS Grid, Multicol, Flexbox
Center an elementHow to center an item horizontally and vertically.Flexbox, Box Alignment
Sticky footersCreating a footer which sits at the bottom of the container or viewport when the content is shorter. CSS Grid, Flexbox
Split navigationA navigation pattern where some links are visually separated from the others.Flexbox, {{cssxref("margin")}}
Breadcrumb navigationCreating a list of links to allow the visitor to navigate back up through the page hierarchy.Flexbox
List group with badgesA list of items with a badge to display a count.Flexbox, Box Alignment
PaginationLinks to pages of content (such as search results).Flexbox, Box Alignment
CardA card component, which displays in a grid of cards.Grid Layout
Grid wrapperFor aligning grid content within a central wrapper, while also allowing items to break out.CSS Grid
+ +

Contribute a Recipe

+ +

As with all of MDN we would love you to contribute a recipe in the same format as the ones shown above. See this page for a template and guidelines for writing your own example.

diff --git a/files/uk/web/css/layout_mode/index.html b/files/uk/web/css/layout_mode/index.html new file mode 100644 index 0000000000..5794b4c397 --- /dev/null +++ b/files/uk/web/css/layout_mode/index.html @@ -0,0 +1,30 @@ +--- +title: Схема компонування +slug: Web/CSS/Схема_компонування +tags: + - CSS + - Компонування + - Розмітка + - Розташування +translation_of: Web/CSS/Layout_mode +--- +
Схема компонування (layout mode) в CSS являє собою алгоритм, який визначає розташування та розміри елементів залежно від того, як вони взаємодіють із сусідніми та батьківськими елементами. Існує декілька таких схем:
+ + + +
+

Зауваження: Не всі властивості CSS застосовні до всіх схем компонування. Більшість із них вживаються разом з однією-двома схемами і жодним чином не діють, якщо відповідний елемент компонується за іншою схемою.

+
+ +

Див. також

+ + diff --git a/files/uk/web/css/reference/index.html b/files/uk/web/css/reference/index.html new file mode 100644 index 0000000000..ba325fe7da --- /dev/null +++ b/files/uk/web/css/reference/index.html @@ -0,0 +1,188 @@ +--- +title: CSS довідник +slug: Web/CSS/Довідник +translation_of: Web/CSS/Reference +--- +

This CSS Reference shows the basic syntax of a CSS rule; lists all standard CSS properties, pseudo-classes and pseudo-elements, @-rules, units, and selectors, all together in alphabetical order, as well as just the selectors by type; and allows you to quickly access detailed information for each of them. It not only lists the CSS 1 and CSS 2.1 properties, but also is a CSS3 reference that links to any CSS3 property and concept standardized, or already stabilized.  Also included is a brief DOM-CSS / CSSOM reference.

+ +

Note that CSS rule-definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM, the rule-management system, is object-based.

+ +

See also Mozilla CSS Extensions for Gecko-specific properties prefixed with -moz; and WebKit CSS Extensions for WebKit-specific properties. See Vendor-prefixed CSS Property Overview by Peter Beverloo for all prefixed properties.

+ +

Basic rule syntax

+ +

Be warned that any syntax error in a rule definition will invalidate the entire rule.

+ +

Style rules

+ +
selectorlist { property: value; [more property:value; pairs] }
+
+...where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
+
+See selector, pseudo-element, pseudo-class lists below.
+
+ +

Examples

+ +
strong { color: red;}
+div.menu-bar li:hover > ul { display: block; }
+
+ +

More about examples: #1, #2

+ +

@rules

+ +

As these have so many different structure-formats, see the desired At-rule for syntax.

+ +

Keyword index

+ +
{{CSS_Ref}}
+ +
+
+

Selectors

+ +
    +
  • Basic Selectors + +
  • +
  • Combinators    (more info) + +
  • +
  • Pseudo-elements    (more info) +
      +
    • {{ Cssxref("::after") }}
    • +
    • {{ Cssxref("::before") }}
    • +
    • {{ Cssxref("::first-letter") }}
    • +
    • {{ Cssxref("::first-line") }}
    • +
    • {{ Cssxref("::selection") }}
    • +
    • {{ Cssxref("::backdrop") }}
    • +
    • {{ Cssxref("::placeholder") }} {{experimental_inline}}
    • +
    • {{ Cssxref("::marker") }} {{experimental_inline}}
    • +
    • {{ Cssxref("::spelling-error") }} {{experimental_inline}}
    • +
    • {{ Cssxref("::grammar-error") }} {{experimental_inline}}
    • +
    +
  • +
  • Standard pseudo-classes    (more info) +
    +
      +
    • {{ Cssxref(":active") }}
    • +
    • {{ cssxref(':any')}}
    • +
    • {{ Cssxref(":checked") }}
    • +
    • {{ Cssxref(":default") }}
    • +
    • {{ Cssxref(":dir", ":dir()")}}
    • +
    • {{ Cssxref(":disabled") }}
    • +
    • {{ Cssxref(":empty") }}
    • +
    • {{ Cssxref(":enabled") }}
    • +
    • {{ Cssxref(":first") }}
    • +
    • {{ Cssxref(":first-child") }}
    • +
    • {{ Cssxref(":first-of-type") }}
    • +
    • {{ Cssxref(":fullscreen") }}
    • +
    • {{ Cssxref(":focus") }}
    • +
    • {{ Cssxref(":hover") }}
    • +
    • {{ Cssxref(":indeterminate") }}
    • +
    • {{ Cssxref(":in-range") }}
    • +
    • {{ Cssxref(":invalid") }}
    • +
    • {{ Cssxref(":lang", ":lang()") }}
    • +
    • {{ Cssxref(":last-child") }}
    • +
    • {{ Cssxref(":last-of-type") }}
    • +
    • {{ Cssxref(":left") }}
    • +
    • {{ Cssxref(":link") }}
    • +
    • {{ Cssxref(":not", ":not()") }}
    • +
    • {{ Cssxref(":nth-child", ":nth-child()") }}
    • +
    • {{ Cssxref(":nth-last-child", ":nth-last-child()") }}
    • +
    • {{ Cssxref(":nth-last-of-type", ":nth-last-of-type()") }}
    • +
    • {{ Cssxref(":nth-of-type", ":nth-of-type()") }}
    • +
    • {{ Cssxref(":only-child") }}
    • +
    • {{ Cssxref(":only-of-type") }}
    • +
    • {{ Cssxref(":optional") }}
    • +
    • {{ Cssxref(":out-of-range") }}
    • +
    • {{ Cssxref(":read-only") }}
    • +
    • {{ Cssxref(":read-write") }}
    • +
    • {{ Cssxref(":required") }}
    • +
    • {{ Cssxref(":right") }}
    • +
    • {{ Cssxref(":root") }}
    • +
    • {{ Cssxref(":scope") }}
    • +
    • {{ Cssxref(":target") }}
    • +
    • {{ Cssxref(":valid") }}
    • +
    • {{ Cssxref(":visited") }}
    • +
    +
    +
  • +
+ +

A complete list of selectors in the Selectors Level 3 specification.

+ +

CSS3 Tutorials

+ +

These small how-to pages describe new technologies appeared in CSS3, or in CSS2.1 but with low support until recently:

+ + + +

Concepts

+ + + +

DOM-CSS / CSSOM

+ +

Major object types:

+ + + +

Important methods:

+ +
    +
  • {{domxref("CSSStyleSheet.insertRule")}}
  • +
  • {{domxref("CSSStyleSheet.deleteRule")}}
  • +
+
+
diff --git a/files/uk/web/css/visual_formatting_model/index.html b/files/uk/web/css/visual_formatting_model/index.html new file mode 100644 index 0000000000..fb25e2d60a --- /dev/null +++ b/files/uk/web/css/visual_formatting_model/index.html @@ -0,0 +1,225 @@ +--- +title: Модель візуального формування +slug: Web/CSS/Модель_візуального_формування +tags: + - CSS + - NeedsUpdate + - Коробчаста модель CSS +translation_of: Web/CSS/Visual_formatting_model +--- +

Модель візуального форматування (visual formatting model) у CSS являє собою алгоритм, що обробляє документ та подає його на візуальному носії. Ця модель є основним поняттям CSS.

+ +

Кожен елемент в документі зазнає перетворення згідно з моделлю візуального формування і породжує нуль (жодного), один або кілька прямокутників відповідно до {{cssxref("CSS_Box_Model/Introduction_to_the_CSS_box_model", "коробчастої моделі")}} CSS. Компонування кожного такого прямокутника визначається низкою чинників:

+ + + +

Відповідно до моделі, прямокутник розміщується й малюється відносно краю блока, всередині якого він міститься. Зазвичай прямокутник утворює такий блок для своїх нащадків. Втім, розмір прямокутника не обмежено розмірами блока, що його містить; коли компонування прямокутника передбачає вихід за межі блока, це зветься {{cssxref("overflow", "переповненням")}}.

+ +

Утворення прямокутників

+ +

Генерація блоків, це частина візуального форматування CSS, що створює прямокутники з елементів документу. Сгенеровані блоки є різних типів, що вплиає на те, як виконується візуальне формування. Тип згенерованого блоку залежить від значення CSS {{ cssxref("display") }}.

+ +

Block-level elements and block boxes

+ +

Елемент  називається блочним, коли його вираховане значення  {{ cssxref("display") }} CSS property is: block, list-item, or table. Елемент рівня блоку візуально форматується, як блок (наприклад абзац), приздачений для вертикальної компановки.

+ +

Each block-level box participates in a block formatting context. Each block-level element generates at least one block-level box, called the principal block-level box. Some elements, like a list-item element, generating further boxes to handle bullets and other typographic elements introducing the list item, may generate more boxes. Most generate only the principal, block-level box.

+ +

The principal block-level box contains descendant-generated boxes and generated content. It is also the box involved in the positioning scheme.

+ +

venn_blocks.pngA block-level box may also be a block container box. A block container box is a box that contains only other block-level boxes, or creates an inline formatting context, thus containing only inline boxes.

+ +

It is important to note that the notions of a block-level box and block container box are disjoined. The first, describes how the box behaves with its parents and sibling. The second, how it interacts with its descendants. Some block-level boxes, like tables, aren't block container boxes. Reciprocally, some block container boxes, like non-replaced inline blocks and non-replaced table cells, aren't block-level boxes.

+ +

Block-level boxes that also are block container boxes are called block boxes.

+ +

Anonymous block boxes

+ +

In some cases, the visual formatting algorithm needs to add supplementary boxes. Because CSS selectors cannot style or name these boxes, they are called anonymous boxes.

+ +

Because selectors do not work with anonymous boxes, they cannot be styled via a stylesheet. This means that all inheritable CSS properties have the inherit value, and all non-inheritable CSS properties, have the initial value.

+ +

Block containing boxes contain only inline-level boxes, or only block-level boxes. But often the document contains a mix of both. In that case, anonymous block boxes are created around adjacent inline-level boxes.

+ +

Example

+ +

If we take the following HTML code (with default styling applied to it, that is {{ HTMLElement("div") }} and {{ HTMLElement("p") }} elements have display:block :

+ +
<div>Some inline text <p>followed by a paragraph</p> followed by more inline text.</div>
+ +

Two anonymous block boxes are created: one for the text before the paragraph (Some inline text), and another for the text after it (followed by more inline text). This builds the following block structure:

+ +

anonymous_block-level_boxes.png

+ +

Leading to:

+ +
Some inline text
+followed by a paragraph
+followed by more inline text.
+
+ +

Unlike the {{ HTMLElement("p") }} element's box, Web developers cannot control the style of the two anonymous boxes. Inheritable properties take the value from the {{ HTMLElement("div") }}'s property value, like {{ cssxref("color") }} to define the color of the text, and set the others to the initial value. For example, they won't have a specific {{ cssxref("background-color") }}, it is always transparent, the initial value for that property, and thus the background of the <div> is visible. A specific background color can be applied to the <p> box. Similarly, the two anonymous boxes always use the same color for their text.

+ +

Another case that leads to the creation of anonymous block boxes, is an inline box that contains one or several block boxes. In that case, the box containing the block box is split into two inline boxes: one before, and one after the block box. All the inline boxes before the block box are then enclosed into an anonymous block box, so are the inline boxes following the block box. Therefore, the block box becomes the sibling of the two anonymous block boxes containing the inline elements.

+ +

If there are several block boxes, without inline content in-between, the anonymous block boxes are created before, and after the set of boxes.

+ +

Example

+ +

If we take the following HTML code, with {{ HTMLElement("p") }} have display:inline and {{ HTMLElement("span") }} have display:block :

+ +
<p>Some <em>inline</em> text <span>followed by a paragraph</span> followed by more inline text.</p>
+ +

Two anonymous block boxes are created, one for the text before the span Element (Some inline text) and one for the text after it (followed by more inline text), which gives the following block structure:

+ +

+ +

Which leads to:

+ +
Some inline text
+followed by a paragraph
+followed by more inline text.
+
+ +

Inline-level elements and inline boxes

+ +

An element is said to be inline-level when the calculated value of its {{ cssxref("display") }} CSS property is: inline, inline-block or inline-table. Visually, it doesn't constitute blocks of contents, but is distributed in lines with other inline-level content. Typically, the content of a paragraph with different formatting, like emphasis or images, is made from inline-level elements.

+ +

venn_inlines.png

+ +
+

This diagram uses outdated terminology; see note below. Besides that, it is incorrect because the yellow ellipsis on the right side is per definition either identical to the one on the left side, or bigger than that (it could be a mathematical superset), because the spec says "Inline-level elements generate inline-level boxes, which are boxes that participate in an inline formatting context", see CSS 2.2, chapter 9.2.2

+
+ +

Inline-level elements generate inline-level boxes that are defined as boxes participating to an inline formatting context. Inline boxes are both inline-level boxes and boxes, whose contents participate in their container's inline formatting context. This is the case, for example, for all non-replaced boxes with display:inline. Inline-level boxes, whose contents do not participate in an inline formatting context, are called atomic inline-level boxes. These boxes, generated by replaced inline-level elements or by elements with a calculated {{ cssxref("display") }} value of inline-block or inline-table, are never split into several boxes, as is possible with inline boxes.

+ +
Note: Initially, atomic inline-level boxes were called atomic inline boxes. This was unfortunate, as they are not inline boxes. This was corrected in an erratum to the spec. Nevertheless, you can harmlessly read atomic inline-level box each time you meet atomic inline box in the literature, as this is only a name change.
+ +
Atomic inline boxes cannot be split into several lines in an inline formatting context. +
+
<style>
+  span {
+    display:inline; /* default value*/
+  }
+</style>
+<div style="width:20em;">
+   The text in the span <span>can be split in several
+   lines as it</span> is an inline box.
+</div>
+
+ +

which leads to:

+ +
The text in the span can be split into several lines as it is an inline box.
+ +
<style>
+  span {
+    display:inline-block;
+  }
+</style>
+<div style="width:20em;">
+   The text in the span <span>cannot be split in several
+   lines as it</span> is an inline-block box.
+</div>
+
+ +

which leads to:

+ +
The text in the span cannot be split into several lines as it is an inline-block box.
+
+
+ +

Anonymous inline boxes

+ +

As for block boxes, there are a few cases where inline boxes are created automatically by the CSS engine. These inline boxes are also anonymous as they cannot be named by selectors; they inherit the value of all inheritable properties, setting it to initial for all others.

+ +

The most common case where an anonymous inline box is created, is when some text is found as a direct child of a block box creating an inline formatting context. In that case, this text is included in the largest possible anonymous inline box. Also, space content, which would be removed by the behavior set in the {{ cssxref("white-space") }} CSS property, does not generate anonymous inline boxes because they would end empty.

+ +
Example TBD
+ +

Other types of boxes

+ +

Line boxes

+ +

Line boxes are generated by the inline formatting context to represent a line of text. Inside a block box, a line box extends from one border of the box to the other. When there are floats, the line box starts at the rightmost border of the left floats and ends at the leftmost border of the right floats.

+ +

These boxes are technical, and Web authors do not usually have to bother with them.

+ +

Run-in boxes

+ +

Run-in boxes, defined using display:run-in, are boxes that are either block boxes or inline boxes, depending on the type of the following box. They can be used to create a title that runs inside its first paragraph when possible.

+ +
Note: Run-in boxes were removed from the CSS 2.1 standard, as they were insufficiently specified to allow for interoperable implementation. They may reappear in CSS3, but meanwhile, are considered experimental. They should not be used in production.
+ +

Model-induced boxes

+ +

Besides the inline and block formatting contexts, CSS specifies several additional content models that may be applied to elements. These additional models, used to describe specific layouts, may define additional box types:

+ + + +

Positioning schemes

+ +

Once boxes are generated, the CSS engine needs to position them on the layout. To do that, it uses one of the following algorithms:

+ + + +

Normal flow

+ +

In the normal flow, boxes are laid out one after the other. In a block formatting context, they are laid out vertically; in an inline formatting context, they are laid out horizontally. The normal flow is triggered when the CSS {{ cssxref("position") }} is set to the value static or relative, and if the CSS {{ cssxref("float") }} is set to the value none.

+ +

Example

+ +
When in the normal flow, in a block formatting context, boxes are laid vertically one after the other out:
+
+[image]
+
+When in the normal flow, in an inline formatting context, boxes are laid horizontally one after the other out:
+
+[image]
+ +

There are two sub-cases of the normal flow: static positioning and relative positioning:

+ + + +

Floats

+ +

In the float positioning scheme, specific boxes (called floating boxes or simply floats) are positioned at the beginning, or end of the current line. This leads to the property that text (and more generally anything within the normal flow) flows along the edge of the floating boxes, except if told differently by the {{ cssxref("clear") }} CSS property.

+ +

The float positioning scheme for a box is selected, by setting the {{ cssxref("float") }} CSS property on that box to a value different than none and {{ cssxref("position") }} to static or relative. If {{ cssxref("float") }} is set to left, the float is positioned at the beginning of the line box. If set to right, the float is positioned at the end of the line box. In either case, the line box is shrunk to fit alongside the float.

+ +

[image]

+ +

Absolute positioning

+ +

In the absolute positioning scheme, boxes are entirely removed from the flow and don't interact with it at all. They are positioned relative to their containing block using the {{ cssxref("top") }}, {{ cssxref("bottom") }}, {{ cssxref("left") }} and {{ cssxref("right") }} CSS properties.

+ +

An element is absolutely positioned if the {{ cssxref("position") }} is set to absolute or fixed.

+ +

With a fixed positioned element, the containing block is the viewport. The position of the element is absolute within the viewport. Scrolling does not change the position of the element.

+ +

Див. також

+ + diff --git "a/files/uk/web/css/\320\260\320\273\321\214\321\202\320\265\321\200\320\275\320\260\321\202\320\270\320\262\320\275\321\226_\321\202\320\260\320\261\320\273\320\270\321\206\321\226_\321\201\321\202\320\270\320\273\321\226\320\262/index.html" "b/files/uk/web/css/\320\260\320\273\321\214\321\202\320\265\321\200\320\275\320\260\321\202\320\270\320\262\320\275\321\226_\321\202\320\260\320\261\320\273\320\270\321\206\321\226_\321\201\321\202\320\270\320\273\321\226\320\262/index.html" deleted file mode 100644 index 1dd1b5a510..0000000000 --- "a/files/uk/web/css/\320\260\320\273\321\214\321\202\320\265\321\200\320\275\320\260\321\202\320\270\320\262\320\275\321\226_\321\202\320\260\320\261\320\273\320\270\321\206\321\226_\321\201\321\202\320\270\320\273\321\226\320\262/index.html" +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Альтернативні таблиці стилів -slug: Web/CSS/Альтернативні_таблиці_стилів -tags: - - Стилі - - Теми -translation_of: Web/CSS/Alternative_style_sheets ---- -

Specifying alternative style sheets in a web page provides a way for users to see multiple versions of a page, based on their needs or preferences.

- -

Firefox lets the user select the stylesheet using the View > Page Style submenu, Internet Explorer also supports this feature (beginning with IE 8), also accessed from View > Page Style (at least as of IE 11), but Chrome requires an extension to use the feature (as of version 48). The web page can also provide its own user interface to let the user switch styles.

- -

An example: specifying the alternative stylesheets

- -

The alternate stylesheets are commonly specified using a {{HTMLElement("link")}} element with rel="stylesheet alternate" and title="..." attributes, for example:

- -
<link href="reset.css" rel="stylesheet" type="text/css">
-
-<link href="default.css" rel="stylesheet" type="text/css" title="Default Style">
-<link href="fancy.css" rel="alternate stylesheet" type="text/css" title="Fancy">
-<link href="basic.css" rel="alternate stylesheet" type="text/css" title="Basic">
-
- -

In this example, the styles "Default Style", "Fancy", and "Basic" will be listed in the Page Style submenu, with the Default Style pre-selected. When the user selects a different style, the page will immediately be re-rendered using that style sheet.

- -

No matter what style is selected, the rules from the reset.css stylesheet will always be applied.

- -

Try it out

- -

Click here for a working example you can try out.

- -

Details

- -

Any stylesheet in a document falls into one of the following categories:

- - - -

When style sheets are referenced with a title attribute on the {{HTMLElement("link", "<link rel=\"stylesheet\">")}} or {{HTMLElement("style")}} element, the title becomes one of the choices offered to the user. Style sheets linked with the same title are part of the same choice. Style sheets linked without a title attribute are always applied.

- -

Use rel="stylesheet" to link to the default style, and rel="alternate stylesheet" to link to alternative style sheets. This tells the browser which style sheet title should be selected by default, and makes that default selection apply in browsers that do not support alternate style sheets.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSSOM', '#css-style-sheet-collections', 'CSS Style Sheet Collections')}}{{Spec2('CSSOM')}}The CSS OM specification defines the concepts of the style sheet set name, its disabled flag, and the preferred CSS style sheet set name.
- It defines how these are determined, and lets the HTML specification define the HTML-specific behaviors by requiring it to define when to create a CSS style sheet.
-

{{SpecName('HTML WHATWG', 'semantics.html#link-type-stylesheet', 'Link type "stylesheet"')}}
- {{SpecName('HTML WHATWG', 'semantics.html#attr-style-title', 'The style element')}}
- {{SpecName('HTML WHATWG', 'semantics.html#attr-meta-http-equiv-default-style', 'Default style state (http-equiv="default-style")')}}

-
{{Spec2('HTML WHATWG')}}The HTML specification defines when and how the create a CSS style sheet algorithm is invoked while handling <link> and <style> elements, and also defines the behavior of <meta http-equiv="default-style">.
{{SpecName("HTML4.01", "present/styles.html#h-14.3", "Alternative style sheets")}}{{Spec2("HTML4.01")}}Earlier, the HTML specification itself defined the concept of preferred and alternate stylesheets.
- -

 

diff --git "a/files/uk/web/css/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" "b/files/uk/web/css/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" deleted file mode 100644 index ba325fe7da..0000000000 --- "a/files/uk/web/css/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: CSS довідник -slug: Web/CSS/Довідник -translation_of: Web/CSS/Reference ---- -

This CSS Reference shows the basic syntax of a CSS rule; lists all standard CSS properties, pseudo-classes and pseudo-elements, @-rules, units, and selectors, all together in alphabetical order, as well as just the selectors by type; and allows you to quickly access detailed information for each of them. It not only lists the CSS 1 and CSS 2.1 properties, but also is a CSS3 reference that links to any CSS3 property and concept standardized, or already stabilized.  Also included is a brief DOM-CSS / CSSOM reference.

- -

Note that CSS rule-definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM, the rule-management system, is object-based.

- -

See also Mozilla CSS Extensions for Gecko-specific properties prefixed with -moz; and WebKit CSS Extensions for WebKit-specific properties. See Vendor-prefixed CSS Property Overview by Peter Beverloo for all prefixed properties.

- -

Basic rule syntax

- -

Be warned that any syntax error in a rule definition will invalidate the entire rule.

- -

Style rules

- -
selectorlist { property: value; [more property:value; pairs] }
-
-...where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
-
-See selector, pseudo-element, pseudo-class lists below.
-
- -

Examples

- -
strong { color: red;}
-div.menu-bar li:hover > ul { display: block; }
-
- -

More about examples: #1, #2

- -

@rules

- -

As these have so many different structure-formats, see the desired At-rule for syntax.

- -

Keyword index

- -
{{CSS_Ref}}
- -
-
-

Selectors

- -
    -
  • Basic Selectors - -
  • -
  • Combinators    (more info) - -
  • -
  • Pseudo-elements    (more info) -
      -
    • {{ Cssxref("::after") }}
    • -
    • {{ Cssxref("::before") }}
    • -
    • {{ Cssxref("::first-letter") }}
    • -
    • {{ Cssxref("::first-line") }}
    • -
    • {{ Cssxref("::selection") }}
    • -
    • {{ Cssxref("::backdrop") }}
    • -
    • {{ Cssxref("::placeholder") }} {{experimental_inline}}
    • -
    • {{ Cssxref("::marker") }} {{experimental_inline}}
    • -
    • {{ Cssxref("::spelling-error") }} {{experimental_inline}}
    • -
    • {{ Cssxref("::grammar-error") }} {{experimental_inline}}
    • -
    -
  • -
  • Standard pseudo-classes    (more info) -
    -
      -
    • {{ Cssxref(":active") }}
    • -
    • {{ cssxref(':any')}}
    • -
    • {{ Cssxref(":checked") }}
    • -
    • {{ Cssxref(":default") }}
    • -
    • {{ Cssxref(":dir", ":dir()")}}
    • -
    • {{ Cssxref(":disabled") }}
    • -
    • {{ Cssxref(":empty") }}
    • -
    • {{ Cssxref(":enabled") }}
    • -
    • {{ Cssxref(":first") }}
    • -
    • {{ Cssxref(":first-child") }}
    • -
    • {{ Cssxref(":first-of-type") }}
    • -
    • {{ Cssxref(":fullscreen") }}
    • -
    • {{ Cssxref(":focus") }}
    • -
    • {{ Cssxref(":hover") }}
    • -
    • {{ Cssxref(":indeterminate") }}
    • -
    • {{ Cssxref(":in-range") }}
    • -
    • {{ Cssxref(":invalid") }}
    • -
    • {{ Cssxref(":lang", ":lang()") }}
    • -
    • {{ Cssxref(":last-child") }}
    • -
    • {{ Cssxref(":last-of-type") }}
    • -
    • {{ Cssxref(":left") }}
    • -
    • {{ Cssxref(":link") }}
    • -
    • {{ Cssxref(":not", ":not()") }}
    • -
    • {{ Cssxref(":nth-child", ":nth-child()") }}
    • -
    • {{ Cssxref(":nth-last-child", ":nth-last-child()") }}
    • -
    • {{ Cssxref(":nth-last-of-type", ":nth-last-of-type()") }}
    • -
    • {{ Cssxref(":nth-of-type", ":nth-of-type()") }}
    • -
    • {{ Cssxref(":only-child") }}
    • -
    • {{ Cssxref(":only-of-type") }}
    • -
    • {{ Cssxref(":optional") }}
    • -
    • {{ Cssxref(":out-of-range") }}
    • -
    • {{ Cssxref(":read-only") }}
    • -
    • {{ Cssxref(":read-write") }}
    • -
    • {{ Cssxref(":required") }}
    • -
    • {{ Cssxref(":right") }}
    • -
    • {{ Cssxref(":root") }}
    • -
    • {{ Cssxref(":scope") }}
    • -
    • {{ Cssxref(":target") }}
    • -
    • {{ Cssxref(":valid") }}
    • -
    • {{ Cssxref(":visited") }}
    • -
    -
    -
  • -
- -

A complete list of selectors in the Selectors Level 3 specification.

- -

CSS3 Tutorials

- -

These small how-to pages describe new technologies appeared in CSS3, or in CSS2.1 but with low support until recently:

- - - -

Concepts

- - - -

DOM-CSS / CSSOM

- -

Major object types:

- - - -

Important methods:

- -
    -
  • {{domxref("CSSStyleSheet.insertRule")}}
  • -
  • {{domxref("CSSStyleSheet.deleteRule")}}
  • -
-
-
diff --git "a/files/uk/web/css/\320\272\320\276\321\200\320\276\320\261\321\207\320\260\321\201\321\202\320\260_\320\274\320\276\320\264\320\265\320\273\321\214_css/index.html" "b/files/uk/web/css/\320\272\320\276\321\200\320\276\320\261\321\207\320\260\321\201\321\202\320\260_\320\274\320\276\320\264\320\265\320\273\321\214_css/index.html" deleted file mode 100644 index 4920b7ceb9..0000000000 --- "a/files/uk/web/css/\320\272\320\276\321\200\320\276\320\261\321\207\320\260\321\201\321\202\320\260_\320\274\320\276\320\264\320\265\320\273\321\214_css/index.html" +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Коробчаста модель CSS -slug: Web/CSS/Коробчаста_модель_CSS -tags: - - CSS - - Довідка - - Коробчаста модель CSS -translation_of: Web/CSS/CSS_Box_Model ---- -
Коробчаста модель (box model) — це алгоритм CSS, що подає елементи (включно з їх {{cssxref("margin", "відступами")}} та {{cssxref("padding", "полями")}}) у вигляді прямокутних «коробок» та компонує їх відповідно до {{cssxref("Visual_formatting_model", "моделі візуального формування")}}.
- -

Довідка

- -

Властивості

- -

Властивості, що визначають потік (flow) вмісту

- -
- -
- -

Властивості, що визначають розміри

- -
- -
- -

Властивості, що визначають відступи

- -
- -
- -

Властивості, що визначають поля

- -
- -
- -

Інші властивості

- -
- -
- -

Посібники

- -
-
Вступ до коробчастої моделі CSS
-
Описує та пояснює одне з ґрунтовних понять в CSS — коробчасту модель. Ця модель визначає, як CSS розташовує елементи, їх вміст, {{cssxref("padding", "поля")}}, {{cssxref("border", "обрамок")}} та {{cssxref("margin", "відступи")}}.
-
Згортання відступів
-
Два прилеглі відступи інколи згортаються в один. Ця стаття наводить правила, за якими це відбувається, та пояснює, як цим керувати.
-
Модель візуального формування
-
Описує та пояснює модель візуального формування.
-
- -

Специфікації

- - - - - - - - - - - - - - - - - - - - - - - - - - -
СпецифікаціяСтатусКоментар
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}} 
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Первинне визначення
- -

Підтримка веб-переглядачами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
-
diff --git "a/files/uk/web/css/\320\274\320\276\320\264\320\265\320\273\321\214_\320\262\321\226\320\267\321\203\320\260\320\273\321\214\320\275\320\276\320\263\320\276_\321\204\320\276\321\200\320\274\321\203\320\262\320\260\320\275\320\275\321\217/index.html" "b/files/uk/web/css/\320\274\320\276\320\264\320\265\320\273\321\214_\320\262\321\226\320\267\321\203\320\260\320\273\321\214\320\275\320\276\320\263\320\276_\321\204\320\276\321\200\320\274\321\203\320\262\320\260\320\275\320\275\321\217/index.html" deleted file mode 100644 index fb25e2d60a..0000000000 --- "a/files/uk/web/css/\320\274\320\276\320\264\320\265\320\273\321\214_\320\262\321\226\320\267\321\203\320\260\320\273\321\214\320\275\320\276\320\263\320\276_\321\204\320\276\321\200\320\274\321\203\320\262\320\260\320\275\320\275\321\217/index.html" +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Модель візуального формування -slug: Web/CSS/Модель_візуального_формування -tags: - - CSS - - NeedsUpdate - - Коробчаста модель CSS -translation_of: Web/CSS/Visual_formatting_model ---- -

Модель візуального форматування (visual formatting model) у CSS являє собою алгоритм, що обробляє документ та подає його на візуальному носії. Ця модель є основним поняттям CSS.

- -

Кожен елемент в документі зазнає перетворення згідно з моделлю візуального формування і породжує нуль (жодного), один або кілька прямокутників відповідно до {{cssxref("CSS_Box_Model/Introduction_to_the_CSS_box_model", "коробчастої моделі")}} CSS. Компонування кожного такого прямокутника визначається низкою чинників:

- - - -

Відповідно до моделі, прямокутник розміщується й малюється відносно краю блока, всередині якого він міститься. Зазвичай прямокутник утворює такий блок для своїх нащадків. Втім, розмір прямокутника не обмежено розмірами блока, що його містить; коли компонування прямокутника передбачає вихід за межі блока, це зветься {{cssxref("overflow", "переповненням")}}.

- -

Утворення прямокутників

- -

Генерація блоків, це частина візуального форматування CSS, що створює прямокутники з елементів документу. Сгенеровані блоки є різних типів, що вплиає на те, як виконується візуальне формування. Тип згенерованого блоку залежить від значення CSS {{ cssxref("display") }}.

- -

Block-level elements and block boxes

- -

Елемент  називається блочним, коли його вираховане значення  {{ cssxref("display") }} CSS property is: block, list-item, or table. Елемент рівня блоку візуально форматується, як блок (наприклад абзац), приздачений для вертикальної компановки.

- -

Each block-level box participates in a block formatting context. Each block-level element generates at least one block-level box, called the principal block-level box. Some elements, like a list-item element, generating further boxes to handle bullets and other typographic elements introducing the list item, may generate more boxes. Most generate only the principal, block-level box.

- -

The principal block-level box contains descendant-generated boxes and generated content. It is also the box involved in the positioning scheme.

- -

venn_blocks.pngA block-level box may also be a block container box. A block container box is a box that contains only other block-level boxes, or creates an inline formatting context, thus containing only inline boxes.

- -

It is important to note that the notions of a block-level box and block container box are disjoined. The first, describes how the box behaves with its parents and sibling. The second, how it interacts with its descendants. Some block-level boxes, like tables, aren't block container boxes. Reciprocally, some block container boxes, like non-replaced inline blocks and non-replaced table cells, aren't block-level boxes.

- -

Block-level boxes that also are block container boxes are called block boxes.

- -

Anonymous block boxes

- -

In some cases, the visual formatting algorithm needs to add supplementary boxes. Because CSS selectors cannot style or name these boxes, they are called anonymous boxes.

- -

Because selectors do not work with anonymous boxes, they cannot be styled via a stylesheet. This means that all inheritable CSS properties have the inherit value, and all non-inheritable CSS properties, have the initial value.

- -

Block containing boxes contain only inline-level boxes, or only block-level boxes. But often the document contains a mix of both. In that case, anonymous block boxes are created around adjacent inline-level boxes.

- -

Example

- -

If we take the following HTML code (with default styling applied to it, that is {{ HTMLElement("div") }} and {{ HTMLElement("p") }} elements have display:block :

- -
<div>Some inline text <p>followed by a paragraph</p> followed by more inline text.</div>
- -

Two anonymous block boxes are created: one for the text before the paragraph (Some inline text), and another for the text after it (followed by more inline text). This builds the following block structure:

- -

anonymous_block-level_boxes.png

- -

Leading to:

- -
Some inline text
-followed by a paragraph
-followed by more inline text.
-
- -

Unlike the {{ HTMLElement("p") }} element's box, Web developers cannot control the style of the two anonymous boxes. Inheritable properties take the value from the {{ HTMLElement("div") }}'s property value, like {{ cssxref("color") }} to define the color of the text, and set the others to the initial value. For example, they won't have a specific {{ cssxref("background-color") }}, it is always transparent, the initial value for that property, and thus the background of the <div> is visible. A specific background color can be applied to the <p> box. Similarly, the two anonymous boxes always use the same color for their text.

- -

Another case that leads to the creation of anonymous block boxes, is an inline box that contains one or several block boxes. In that case, the box containing the block box is split into two inline boxes: one before, and one after the block box. All the inline boxes before the block box are then enclosed into an anonymous block box, so are the inline boxes following the block box. Therefore, the block box becomes the sibling of the two anonymous block boxes containing the inline elements.

- -

If there are several block boxes, without inline content in-between, the anonymous block boxes are created before, and after the set of boxes.

- -

Example

- -

If we take the following HTML code, with {{ HTMLElement("p") }} have display:inline and {{ HTMLElement("span") }} have display:block :

- -
<p>Some <em>inline</em> text <span>followed by a paragraph</span> followed by more inline text.</p>
- -

Two anonymous block boxes are created, one for the text before the span Element (Some inline text) and one for the text after it (followed by more inline text), which gives the following block structure:

- -

- -

Which leads to:

- -
Some inline text
-followed by a paragraph
-followed by more inline text.
-
- -

Inline-level elements and inline boxes

- -

An element is said to be inline-level when the calculated value of its {{ cssxref("display") }} CSS property is: inline, inline-block or inline-table. Visually, it doesn't constitute blocks of contents, but is distributed in lines with other inline-level content. Typically, the content of a paragraph with different formatting, like emphasis or images, is made from inline-level elements.

- -

venn_inlines.png

- -
-

This diagram uses outdated terminology; see note below. Besides that, it is incorrect because the yellow ellipsis on the right side is per definition either identical to the one on the left side, or bigger than that (it could be a mathematical superset), because the spec says "Inline-level elements generate inline-level boxes, which are boxes that participate in an inline formatting context", see CSS 2.2, chapter 9.2.2

-
- -

Inline-level elements generate inline-level boxes that are defined as boxes participating to an inline formatting context. Inline boxes are both inline-level boxes and boxes, whose contents participate in their container's inline formatting context. This is the case, for example, for all non-replaced boxes with display:inline. Inline-level boxes, whose contents do not participate in an inline formatting context, are called atomic inline-level boxes. These boxes, generated by replaced inline-level elements or by elements with a calculated {{ cssxref("display") }} value of inline-block or inline-table, are never split into several boxes, as is possible with inline boxes.

- -
Note: Initially, atomic inline-level boxes were called atomic inline boxes. This was unfortunate, as they are not inline boxes. This was corrected in an erratum to the spec. Nevertheless, you can harmlessly read atomic inline-level box each time you meet atomic inline box in the literature, as this is only a name change.
- -
Atomic inline boxes cannot be split into several lines in an inline formatting context. -
-
<style>
-  span {
-    display:inline; /* default value*/
-  }
-</style>
-<div style="width:20em;">
-   The text in the span <span>can be split in several
-   lines as it</span> is an inline box.
-</div>
-
- -

which leads to:

- -
The text in the span can be split into several lines as it is an inline box.
- -
<style>
-  span {
-    display:inline-block;
-  }
-</style>
-<div style="width:20em;">
-   The text in the span <span>cannot be split in several
-   lines as it</span> is an inline-block box.
-</div>
-
- -

which leads to:

- -
The text in the span cannot be split into several lines as it is an inline-block box.
-
-
- -

Anonymous inline boxes

- -

As for block boxes, there are a few cases where inline boxes are created automatically by the CSS engine. These inline boxes are also anonymous as they cannot be named by selectors; they inherit the value of all inheritable properties, setting it to initial for all others.

- -

The most common case where an anonymous inline box is created, is when some text is found as a direct child of a block box creating an inline formatting context. In that case, this text is included in the largest possible anonymous inline box. Also, space content, which would be removed by the behavior set in the {{ cssxref("white-space") }} CSS property, does not generate anonymous inline boxes because they would end empty.

- -
Example TBD
- -

Other types of boxes

- -

Line boxes

- -

Line boxes are generated by the inline formatting context to represent a line of text. Inside a block box, a line box extends from one border of the box to the other. When there are floats, the line box starts at the rightmost border of the left floats and ends at the leftmost border of the right floats.

- -

These boxes are technical, and Web authors do not usually have to bother with them.

- -

Run-in boxes

- -

Run-in boxes, defined using display:run-in, are boxes that are either block boxes or inline boxes, depending on the type of the following box. They can be used to create a title that runs inside its first paragraph when possible.

- -
Note: Run-in boxes were removed from the CSS 2.1 standard, as they were insufficiently specified to allow for interoperable implementation. They may reappear in CSS3, but meanwhile, are considered experimental. They should not be used in production.
- -

Model-induced boxes

- -

Besides the inline and block formatting contexts, CSS specifies several additional content models that may be applied to elements. These additional models, used to describe specific layouts, may define additional box types:

- - - -

Positioning schemes

- -

Once boxes are generated, the CSS engine needs to position them on the layout. To do that, it uses one of the following algorithms:

- - - -

Normal flow

- -

In the normal flow, boxes are laid out one after the other. In a block formatting context, they are laid out vertically; in an inline formatting context, they are laid out horizontally. The normal flow is triggered when the CSS {{ cssxref("position") }} is set to the value static or relative, and if the CSS {{ cssxref("float") }} is set to the value none.

- -

Example

- -
When in the normal flow, in a block formatting context, boxes are laid vertically one after the other out:
-
-[image]
-
-When in the normal flow, in an inline formatting context, boxes are laid horizontally one after the other out:
-
-[image]
- -

There are two sub-cases of the normal flow: static positioning and relative positioning:

- - - -

Floats

- -

In the float positioning scheme, specific boxes (called floating boxes or simply floats) are positioned at the beginning, or end of the current line. This leads to the property that text (and more generally anything within the normal flow) flows along the edge of the floating boxes, except if told differently by the {{ cssxref("clear") }} CSS property.

- -

The float positioning scheme for a box is selected, by setting the {{ cssxref("float") }} CSS property on that box to a value different than none and {{ cssxref("position") }} to static or relative. If {{ cssxref("float") }} is set to left, the float is positioned at the beginning of the line box. If set to right, the float is positioned at the end of the line box. In either case, the line box is shrunk to fit alongside the float.

- -

[image]

- -

Absolute positioning

- -

In the absolute positioning scheme, boxes are entirely removed from the flow and don't interact with it at all. They are positioned relative to their containing block using the {{ cssxref("top") }}, {{ cssxref("bottom") }}, {{ cssxref("left") }} and {{ cssxref("right") }} CSS properties.

- -

An element is absolutely positioned if the {{ cssxref("position") }} is set to absolute or fixed.

- -

With a fixed positioned element, the containing block is the viewport. The position of the element is absolute within the viewport. Scrolling does not change the position of the element.

- -

Див. також

- - diff --git "a/files/uk/web/css/\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260_\320\272\321\203\320\273\321\226\320\275\320\260\321\200\320\275\320\260-\320\272\320\275\320\270\320\263\320\260/index.html" "b/files/uk/web/css/\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260_\320\272\321\203\320\273\321\226\320\275\320\260\321\200\320\275\320\260-\320\272\320\275\320\270\320\263\320\260/index.html" deleted file mode 100644 index e6d7f61135..0000000000 --- "a/files/uk/web/css/\321\200\320\276\320\267\320\274\321\226\321\202\320\272\320\260_\320\272\321\203\320\273\321\226\320\275\320\260\321\200\320\275\320\260-\320\272\320\275\320\270\320\263\320\260/index.html" +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Кулінарна книга з CSS розмітки -slug: Web/CSS/Розмітка_кулінарна-книга -translation_of: Web/CSS/Layout_cookbook ---- -
{{CSSRef}}
- -

The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.

- -
-

Note: If you are new to CSS layout then you might first like to take a look at our CSS layout learning module, as this will give you the basic grounding you need to make use of the recipes here.

-
- -

The Recipes

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RecipeDescriptionLayout Methods
Media objectsA two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet.CSS Grid, {{cssxref("float")}} fallback, {{cssxref("fit-content")}} sizing
ColumnsWhen to choose multi-column layout, flexbox or grid for your columns.CSS Grid, Multicol, Flexbox
Center an elementHow to center an item horizontally and vertically.Flexbox, Box Alignment
Sticky footersCreating a footer which sits at the bottom of the container or viewport when the content is shorter. CSS Grid, Flexbox
Split navigationA navigation pattern where some links are visually separated from the others.Flexbox, {{cssxref("margin")}}
Breadcrumb navigationCreating a list of links to allow the visitor to navigate back up through the page hierarchy.Flexbox
List group with badgesA list of items with a badge to display a count.Flexbox, Box Alignment
PaginationLinks to pages of content (such as search results).Flexbox, Box Alignment
CardA card component, which displays in a grid of cards.Grid Layout
Grid wrapperFor aligning grid content within a central wrapper, while also allowing items to break out.CSS Grid
- -

Contribute a Recipe

- -

As with all of MDN we would love you to contribute a recipe in the same format as the ones shown above. See this page for a template and guidelines for writing your own example.

diff --git "a/files/uk/web/css/\321\201\321\205\320\265\320\274\320\260_\320\272\320\276\320\274\320\277\320\276\320\275\321\203\320\262\320\260\320\275\320\275\321\217/index.html" "b/files/uk/web/css/\321\201\321\205\320\265\320\274\320\260_\320\272\320\276\320\274\320\277\320\276\320\275\321\203\320\262\320\260\320\275\320\275\321\217/index.html" deleted file mode 100644 index 5794b4c397..0000000000 --- "a/files/uk/web/css/\321\201\321\205\320\265\320\274\320\260_\320\272\320\276\320\274\320\277\320\276\320\275\321\203\320\262\320\260\320\275\320\275\321\217/index.html" +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Схема компонування -slug: Web/CSS/Схема_компонування -tags: - - CSS - - Компонування - - Розмітка - - Розташування -translation_of: Web/CSS/Layout_mode ---- -
Схема компонування (layout mode) в CSS являє собою алгоритм, який визначає розташування та розміри елементів залежно від того, як вони взаємодіють із сусідніми та батьківськими елементами. Існує декілька таких схем:
- - - -
-

Зауваження: Не всі властивості CSS застосовні до всіх схем компонування. Більшість із них вживаються разом з однією-двома схемами і жодним чином не діють, якщо відповідний елемент компонується за іншою схемою.

-
- -

Див. також

- - -- cgit v1.2.3-54-g00ecf