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 --- .../index.html" | 201 ----- .../hit_regions_and_accessibility/index.html | 108 +++ .../index.html" | 108 --- files/uk/web/api/event/index.html | 188 +++++ files/uk/web/api/event/target/index.html | 134 +++ .../api/htmlmediaelement/abort_event/index.html | 68 ++ files/uk/web/api/page_visibility_api/index.html | 201 +++++ .../api/window/domcontentloaded_event/index.html | 152 ++++ .../settimeout/index.html | 428 ++++++++++ files/uk/web/api/windowtimers/index.html | 126 --- .../uk/web/api/windowtimers/settimeout/index.html | 428 ---------- .../index.html" | 188 ----- .../target/index.html" | 134 --- .../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 - files/uk/web/events/abort/index.html | 68 -- files/uk/web/events/domcontentloaded/index.html | 152 ---- files/uk/web/guide/css/getting_started/index.html | 47 -- .../css/getting_started/what_is_css/index.html | 114 --- files/uk/web/guide/graphics/index.html | 49 ++ .../using_html_sections_and_outlines/index.html | 337 ++++++++ .../index.html" | 337 -------- .../index.html" | 49 -- files/uk/web/houdini/index.html | 87 ++ files/uk/web/html/element/header/index.html | 145 ++++ files/uk/web/html/element/html/index.html | 169 ++++ files/uk/web/html/element/iframe/index.html | 260 ++++++ files/uk/web/html/element/index.html | 96 +++ files/uk/web/html/element/link/index.html | 325 ++++++++ files/uk/web/html/element/nav/index.html | 99 +++ files/uk/web/html/element/script/index.html | 243 ++++++ files/uk/web/html/element/section/index.html | 173 ++++ files/uk/web/html/element/style/index.html | 201 +++++ files/uk/web/html/element/table/index.html | 371 +++++++++ files/uk/web/html/element/video/index.html | 420 ++++++++++ .../web/html/global_attributes/hidden/index.html | 68 ++ files/uk/web/html/global_attributes/index.html | 474 +++++++++++ .../html/global_attributes/itemscope/index.html | 319 +++++++ .../uk/web/html/global_attributes/lang/index.html | 90 ++ .../web/html/global_attributes/tabindex/index.html | 96 +++ .../html/quirks_mode_and_standards_mode/index.html | 46 + files/uk/web/html/reference/index.html | 27 + .../index.html" | 27 - .../html/index.html" | 169 ---- .../iframe/index.html" | 260 ------ .../index.html" | 96 --- .../link/index.html" | 325 -------- .../nav/index.html" | 99 --- .../script/index.html" | 243 ------ .../section/index.html" | 173 ---- .../style/index.html" | 201 ----- .../table/index.html" | 371 --------- .../video/index.html" | 420 ---------- .../index.html" | 145 ---- .../hidden/index.html" | 68 -- .../index.html" | 474 ----------- .../itemscope/index.html" | 319 ------- .../lang/index.html" | 90 -- .../tabindex/index.html" | 96 --- .../index.html" | 46 - .../uk/web/http/headers/accept-encoding/index.html | 109 +++ .../uk/web/http/headers/accept-language/index.html | 94 +++ files/uk/web/http/headers/connection/index.html | 46 + .../uk/web/http/headers/content-length/index.html | 62 ++ files/uk/web/http/headers/content-type/index.html | 113 +++ files/uk/web/http/headers/etag/index.html | 98 +++ files/uk/web/http/headers/if-match/index.html | 86 ++ files/uk/web/http/headers/index.html | 382 +++++++++ files/uk/web/http/headers/location/index.html | 78 ++ files/uk/web/http/headers/referer/index.html | 80 ++ files/uk/web/http/headers/user-agent/index.html | 133 +++ .../web/http/headers/x-forwarded-proto/index.html | 69 ++ .../accept-encoding/index.html" | 109 --- .../accept-language/index.html" | 94 --- .../connection/index.html" | 46 - .../content-length/index.html" | 62 -- .../content-type/index.html" | 113 --- .../etag/index.html" | 98 --- .../if-match/index.html" | 86 -- .../index.html" | 382 --------- .../location/index.html" | 78 -- .../referer/index.html" | 80 -- .../user-agent/index.html" | 133 --- .../x-forwarded-proto/index.html" | 69 -- .../equality_comparisons_and_sameness/index.html | 494 +++++++++++ .../guide/details_of_the_object_model/index.html | 760 +++++++++++++++++ .../guide/dokladno_pro_objectnu_model/index.html | 760 ----------------- .../guide/expressions_and_operators/index.html | 925 +++++++++++++++++++++ .../index.html" | 925 --------------------- .../javascript_technologies_overview/index.html | 87 ++ .../oglyad_tehnologiy_javascript/index.html | 87 -- .../reference/functions/arrow_functions/index.html | 362 ++++++++ .../reference/functions/rest_parameters/index.html | 211 +++++ .../index.html" | 211 ----- .../index.html" | 362 -------- .../global_objects/array/prototype/index.html | 185 ----- .../asyncfunction/prototype/index.html | 59 -- .../global_objects/boolean/prototype/index.html | 83 -- .../global_objects/error/prototype/index.html | 115 --- .../global_objects/evalerror/prototype/index.html | 90 -- .../global_objects/function/prototype/index.html | 100 --- .../generatorfunction/prototype/index.html | 66 -- .../internalerror/prototype/index.html | 63 -- .../reference/global_objects/math/round/index.html | 194 +++++ .../index.html" | 194 ----- .../global_objects/number/epsilon/index.html | 67 ++ .../reference/global_objects/number/index.html | 186 +++++ .../global_objects/number/isfinite/index.html | 86 ++ .../global_objects/number/isinteger/index.html | 94 +++ .../global_objects/number/isnan/index.html | 100 +++ .../global_objects/number/issafeinteger/index.html | 95 +++ .../number/max_safe_integer/index.html | 78 ++ .../global_objects/number/max_value/index.html | 64 ++ .../number/min_safe_integer/index.html | 62 ++ .../global_objects/number/min_value/index.html | 66 ++ .../reference/global_objects/number/nan/index.html | 59 ++ .../number/negative_infinity/index.html | 82 ++ .../global_objects/number/number/index.html | 63 ++ .../global_objects/number/parsefloat/index.html | 88 ++ .../global_objects/number/parseint/index.html | 83 ++ .../number/positive_infinity/index.html | 82 ++ .../global_objects/number/toexponential/index.html | 89 ++ .../global_objects/number/tofixed/index.html | 95 +++ .../number/tolocalestring/index.html | 154 ++++ .../global_objects/number/toprecision/index.html | 88 ++ .../global_objects/number/tosource/index.html | 54 ++ .../global_objects/number/tostring/index.html | 97 +++ .../global_objects/number/valueof/index.html | 67 ++ .../global_objects/promise/prototype/index.html | 70 -- .../global_objects/promise/reject/index.html | 73 ++ .../index.html" | 73 -- .../global_objects/rangeerror/prototype/index.html | 90 -- .../referenceerror/prototype/index.html | 91 -- .../syntaxerror/prototype/index.html | 89 -- .../global_objects/typeerror/prototype/index.html | 88 -- .../global_objects/urierror/prototype/index.html | 89 -- .../epsilon/index.html" | 67 -- .../index.html" | 186 ----- .../isfinite/index.html" | 86 -- .../isinteger/index.html" | 94 --- .../isnan/index.html" | 100 --- .../issafeinteger/index.html" | 95 --- .../max_safe_integer/index.html" | 78 -- .../max_value/index.html" | 64 -- .../min_safe_integer/index.html" | 62 -- .../min_value/index.html" | 66 -- .../nan/index.html" | 59 -- .../negative_infinity/index.html" | 82 -- .../number/index.html" | 63 -- .../parsefloat/index.html" | 88 -- .../parseint/index.html" | 83 -- .../positive_infinity/index.html" | 82 -- .../prototype/index.html" | 90 -- .../toexponential/index.html" | 89 -- .../tofixed/index.html" | 95 --- .../tolocalestring/index.html" | 154 ---- .../toprecision/index.html" | 88 -- .../tosource/index.html" | 54 -- .../tostring/index.html" | 97 --- .../valueof/index.html" | 67 -- .../reference/iteration_protocols/index.html | 352 ++++++++ .../operators/arithmetic_operators/index.html | 314 ------- .../operators/bitwise_operators/index.html | 560 ------------- .../operators/destructuring_assignment/index.html | 453 ++++++++++ .../operators/logical_operators/index.html | 253 ------ .../operators/object_initializer/index.html | 296 +++++++ .../index.html" | 453 ---------- .../index.html" | 283 ------- .../index.html" | 245 ------ .../index.html" | 419 ---------- .../index.html" | 296 ------- .../reference/statements/default/index.html | 118 --- .../index.html" | 352 -------- .../index.html" | 494 ----------- files/uk/web/tutorials/index.html | 184 ++++ .../index.html" | 87 -- .../index.html" | 184 ---- 193 files changed, 14716 insertions(+), 18563 deletions(-) delete mode 100644 "files/uk/web/api/api_\320\262\321\226\320\264\320\276\320\261\321\200\320\260\320\266\320\265\320\275\320\275\321\217_\321\201\321\202\320\276\321\200\321\226\320\275\320\272\320\270/index.html" create mode 100644 files/uk/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html delete mode 100644 "files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" create mode 100644 files/uk/web/api/event/index.html create mode 100644 files/uk/web/api/event/target/index.html create mode 100644 files/uk/web/api/htmlmediaelement/abort_event/index.html create mode 100644 files/uk/web/api/page_visibility_api/index.html create mode 100644 files/uk/web/api/window/domcontentloaded_event/index.html create mode 100644 files/uk/web/api/windoworworkerglobalscope/settimeout/index.html delete mode 100644 files/uk/web/api/windowtimers/index.html delete mode 100644 files/uk/web/api/windowtimers/settimeout/index.html delete mode 100644 "files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/index.html" delete mode 100644 "files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/target/index.html" 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" delete mode 100644 files/uk/web/events/abort/index.html delete mode 100644 files/uk/web/events/domcontentloaded/index.html delete mode 100644 files/uk/web/guide/css/getting_started/index.html delete mode 100644 files/uk/web/guide/css/getting_started/what_is_css/index.html create mode 100644 files/uk/web/guide/graphics/index.html create mode 100644 files/uk/web/guide/html/using_html_sections_and_outlines/index.html delete mode 100644 "files/uk/web/guide/html/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_html-\321\201\320\265\320\272\321\206\321\226\320\271_\321\202\320\260_\321\201\321\202\321\200\321\203\320\272\321\202\321\203\321\200\320\260_\320\264\320\276\320\272\321\203\320\274\320\265\320\275\321\202\321\203/index.html" delete mode 100644 "files/uk/web/guide/\320\263\321\200\320\260\321\204\321\226\320\272\320\260/index.html" create mode 100644 files/uk/web/houdini/index.html create mode 100644 files/uk/web/html/element/header/index.html create mode 100644 files/uk/web/html/element/html/index.html create mode 100644 files/uk/web/html/element/iframe/index.html create mode 100644 files/uk/web/html/element/index.html create mode 100644 files/uk/web/html/element/link/index.html create mode 100644 files/uk/web/html/element/nav/index.html create mode 100644 files/uk/web/html/element/script/index.html create mode 100644 files/uk/web/html/element/section/index.html create mode 100644 files/uk/web/html/element/style/index.html create mode 100644 files/uk/web/html/element/table/index.html create mode 100644 files/uk/web/html/element/video/index.html create mode 100644 files/uk/web/html/global_attributes/hidden/index.html create mode 100644 files/uk/web/html/global_attributes/index.html create mode 100644 files/uk/web/html/global_attributes/itemscope/index.html create mode 100644 files/uk/web/html/global_attributes/lang/index.html create mode 100644 files/uk/web/html/global_attributes/tabindex/index.html create mode 100644 files/uk/web/html/quirks_mode_and_standards_mode/index.html create mode 100644 files/uk/web/html/reference/index.html delete mode 100644 "files/uk/web/html/\320\264\320\276\320\262\321\226\320\264\320\275\320\270\320\272/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/html/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/iframe/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/link/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/nav/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/script/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/section/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/style/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/table/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/video/index.html" delete mode 100644 "files/uk/web/html/\320\265\320\273\320\265\320\274\320\265\320\275\321\202/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\276\320\272/index.html" delete mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/hidden/index.html" delete mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/index.html" delete mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/itemscope/index.html" delete mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/lang/index.html" delete mode 100644 "files/uk/web/html/\320\267\320\260\320\263\320\260\320\273\321\214\320\275\321\226_\320\260\321\202\321\200\320\270\320\261\321\203\321\202\320\270/tabindex/index.html" delete mode 100644 "files/uk/web/html/\321\200\320\265\320\266\320\270\320\274_\321\201\321\203\320\274\321\226\321\201\320\275\320\276\321\201\321\202\321\226_\320\271_\321\201\321\202\320\260\320\275\320\264\320\260\321\200\321\202\320\275\320\270\320\271_\321\200\320\265\320\266\320\270\320\274/index.html" create mode 100644 files/uk/web/http/headers/accept-encoding/index.html create mode 100644 files/uk/web/http/headers/accept-language/index.html create mode 100644 files/uk/web/http/headers/connection/index.html create mode 100644 files/uk/web/http/headers/content-length/index.html create mode 100644 files/uk/web/http/headers/content-type/index.html create mode 100644 files/uk/web/http/headers/etag/index.html create mode 100644 files/uk/web/http/headers/if-match/index.html create mode 100644 files/uk/web/http/headers/index.html create mode 100644 files/uk/web/http/headers/location/index.html create mode 100644 files/uk/web/http/headers/referer/index.html create mode 100644 files/uk/web/http/headers/user-agent/index.html create mode 100644 files/uk/web/http/headers/x-forwarded-proto/index.html delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/accept-encoding/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/accept-language/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/connection/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/content-length/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/content-type/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/etag/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/if-match/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/location/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/referer/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/user-agent/index.html" delete mode 100644 "files/uk/web/http/\320\267\320\260\320\263\320\276\320\273\320\276\320\262\320\272\320\270/x-forwarded-proto/index.html" create mode 100644 files/uk/web/javascript/equality_comparisons_and_sameness/index.html create mode 100644 files/uk/web/javascript/guide/details_of_the_object_model/index.html delete mode 100644 files/uk/web/javascript/guide/dokladno_pro_objectnu_model/index.html create mode 100644 files/uk/web/javascript/guide/expressions_and_operators/index.html delete mode 100644 "files/uk/web/javascript/guide/\320\262\320\270\321\200\320\260\320\267\320\270_\321\202\320\260_\320\276\320\277\320\265\321\200\320\260\321\202\320\276\321\200\320\270/index.html" create mode 100644 files/uk/web/javascript/javascript_technologies_overview/index.html delete mode 100644 files/uk/web/javascript/oglyad_tehnologiy_javascript/index.html create mode 100644 files/uk/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/uk/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 "files/uk/web/javascript/reference/functions/\321\200\320\265\321\210\321\202\320\260_\320\277\320\260\321\200\320\260\320\274\320\265\321\202\321\200\321\226\320\262/index.html" delete mode 100644 "files/uk/web/javascript/reference/functions/\321\201\321\202\321\200\321\226\320\273\320\272\320\276\320\262\321\226_\321\204\321\203\320\275\320\272\321\206\321\226\321\227/index.html" delete mode 100644 files/uk/web/javascript/reference/global_objects/array/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/boolean/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/error/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/evalerror/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/function/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/generatorfunction/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/internalerror/prototype/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/math/round/index.html delete mode 100644 "files/uk/web/javascript/reference/global_objects/math/\320\267\320\260\320\276\320\272\321\200\321\203\320\263\320\265\320\273\320\275\320\275\321\217/index.html" create mode 100644 files/uk/web/javascript/reference/global_objects/number/epsilon/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/issafeinteger/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/max_safe_integer/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/min_safe_integer/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/number/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/parsefloat/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/parseint/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/positive_infinity/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/tolocalestring/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/toprecision/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/tosource/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/number/valueof/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/uk/web/javascript/reference/global_objects/promise/reject/index.html delete mode 100644 "files/uk/web/javascript/reference/global_objects/promise/\320\262\321\226\320\264\321\205\320\270\320\273\320\265\320\275\320\276/index.html" delete mode 100644 files/uk/web/javascript/reference/global_objects/rangeerror/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/referenceerror/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/syntaxerror/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/typeerror/prototype/index.html delete mode 100644 files/uk/web/javascript/reference/global_objects/urierror/prototype/index.html delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/epsilon/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/isfinite/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/isinteger/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/isnan/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/issafeinteger/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/max_safe_integer/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/max_value/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/min_safe_integer/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/min_value/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/nan/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/negative_infinity/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/number/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/parsefloat/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/parseint/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/positive_infinity/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/prototype/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/toexponential/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/tofixed/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/tolocalestring/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/toprecision/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/tosource/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/tostring/index.html" delete mode 100644 "files/uk/web/javascript/reference/global_objects/\321\207\320\270\321\201\320\273\320\276/valueof/index.html" create mode 100644 files/uk/web/javascript/reference/iteration_protocols/index.html delete mode 100644 files/uk/web/javascript/reference/operators/arithmetic_operators/index.html delete mode 100644 files/uk/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/uk/web/javascript/reference/operators/destructuring_assignment/index.html delete mode 100644 files/uk/web/javascript/reference/operators/logical_operators/index.html create mode 100644 files/uk/web/javascript/reference/operators/object_initializer/index.html delete mode 100644 "files/uk/web/javascript/reference/operators/\320\264\320\265\321\201\321\202\321\200\321\203\320\272\321\202\321\203\321\200\320\270\320\267\320\260\321\206\321\226\321\217/index.html" delete mode 100644 "files/uk/web/javascript/reference/operators/\320\276\320\277\320\265\321\200\320\260\321\202\320\276\321\200_\321\200\320\276\320\267\320\277\320\260\320\272\321\203\320\262\320\260\320\275\320\275\321\217/index.html" delete mode 100644 "files/uk/web/javascript/reference/operators/\320\276\320\277\320\265\321\200\320\260\321\202\320\276\321\200\320\270_\320\277\320\276\321\200\321\226\320\262\320\275\321\217\320\275\320\275\321\217/index.html" delete mode 100644 "files/uk/web/javascript/reference/operators/\320\276\320\277\320\265\321\200\320\260\321\202\320\276\321\200\320\270_\320\277\321\200\320\270\321\201\320\262\320\276\321\224\320\275\320\275\321\217/index.html" delete mode 100644 "files/uk/web/javascript/reference/operators/\321\226\320\275\321\226\321\206\321\226\320\260\320\273\321\226\320\267\320\260\321\206\321\226\321\217_\320\276\320\261\342\200\231\321\224\320\272\321\202\321\226\320\262/index.html" delete mode 100644 files/uk/web/javascript/reference/statements/default/index.html delete mode 100644 "files/uk/web/javascript/reference/\320\277\321\200\320\276\321\202\320\276\320\272\320\276\320\273\320\270_\320\277\320\265\321\200\320\265\320\261\320\276\321\200\321\203/index.html" delete mode 100644 "files/uk/web/javascript/\320\277\320\265\321\200\320\265\320\262\321\226\321\200\320\272\320\260_\320\275\320\260_\321\200\321\226\320\262\320\275\321\226\321\201\321\202\321\214_\321\202\320\260_\320\276\320\264\320\275\320\260\320\272\320\276\320\262\321\226\321\201\321\202\321\214/index.html" create mode 100644 files/uk/web/tutorials/index.html delete mode 100644 "files/uk/web/\320\263\321\203\320\264\321\226\320\275\321\226/index.html" delete mode 100644 "files/uk/web/\320\277\320\276\321\201\321\226\320\261\320\275\320\270\320\272\320\270/index.html" (limited to 'files/uk/web') diff --git "a/files/uk/web/api/api_\320\262\321\226\320\264\320\276\320\261\321\200\320\260\320\266\320\265\320\275\320\275\321\217_\321\201\321\202\320\276\321\200\321\226\320\275\320\272\320\270/index.html" "b/files/uk/web/api/api_\320\262\321\226\320\264\320\276\320\261\321\200\320\260\320\266\320\265\320\275\320\275\321\217_\321\201\321\202\320\276\321\200\321\226\320\275\320\272\320\270/index.html" deleted file mode 100644 index 6675a3783b..0000000000 --- "a/files/uk/web/api/api_\320\262\321\226\320\264\320\276\320\261\321\200\320\260\320\266\320\265\320\275\320\275\321\217_\321\201\321\202\320\276\321\200\321\226\320\275\320\272\320\270/index.html" +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: API відображення сторінки -slug: Web/API/API_відображення_сторінки -tags: - - API - - API відображення сторінки - - visibilityState - - visibilitychange - - відображення сторінки - - процеси скритої закладки - - фоновий режим -translation_of: Web/API/Page_Visibility_API ---- -
{{DefaultAPISidebar("Page Visibility API")}}
- -
- -

При перегляді сайту за допомогою вкладок існує ймовірність того, що будь-яка з веб-сторінок знаходиться в фоновому режимі і тому користувач її не бачить. API відображення сторінки надає події, які ви можете відстежити, щоб дізнатися, коли документ стає видимим або прихованим, а також дозволяє отримати поточний стан прихованості/видимості сторінки.

- -
-

Примітка: API відображення сторінки є особливо корисним для економії ресурсів та підвищення продуктивності, дозволяючи сторінці уникнути виконання непотрібних завдань, коли документ не є видимим.

-
- -

Коли користувач згортає вікно або перемикається на іншу вкладку, API посилає подію {{event("visibilitychange")}}, щоб передати слухачам інформацію про зміну стану сторінки. Ви можете виявити подію і виконати деякі дії або нічого не виконувати. Наприклад, якщо ваш веб-додаток програє відео, він може поставити відео на паузу, коли користувач переміщує вкладку у фоновий режим, і відновити відтворення, коли користувач повернеться до цієї вкладки. Користувач не втрачає миті у відео, звук відео не заважає аудіо в новій вкладці на передньому плані, і користувач не пропустить жодного моменту в них.

- -

Стан видимості {{HTMLElement ("iframe")}} збігаються зі станом батьківського документа. Приховування <iframe> за допомогою властивостей CSS (таких як {{cssxref ("display", "display: none;")}}) не викликає подій видимості і не змінює стан документа, що міститься в кадрі.

- -

Випадки використання

- -

Розглянемо декілька прикладів використання API видимості сторінки.

- - - -

Розробники у минулому використовували недосконалі проксі для виявлення цього. Наприклад, перегляд {{event("blur")}} і {{event("focus")}} подій на вікні допомагає зрозуміти, коли ваша сторінка не є активною, але не говорить про те, що ваша сторінка насправді прихована для користувача. API Видимість сторінки вирішує цю проблему.

- -
-

Примітка: У той час як {{domxref ("GlobalEventHandlers.onblur", "onblur")}} та {{domxref ("GlobalEventHandlers.onfocus", "onfocus")}} скажуть вам, коли користувач перемикає вікно, але це не обов'язково означає, що воно приховано. Сторінки стають прихованими тільки тоді, коли користувач перемикає вкладки або згортає вікно браузера, що містить вкладку.

-
- -

Політика позиціонування, як сприяння продуктивності фонової сторінки

- -

Окремо від API відображення сторінки агенти  користувача зазвичай мають ряд власних політик для зниження впливу продуктивності фонових або прихованих вкладок. Вони можуть включати в себе:

- - - -

Деякі процеси виключені з цього гасящего режиму. У цих випадках ви також можете використовувати API видимості сторінки, щоб зменшити вплив на продуктивність.

- - - -

Приклад

- -

Подивіться живий приклад (відео зі звуком).

- -

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

- -
   // Встановіть ім'я властивості hidden і події зміни для видимості.
-
-var hidden, visibilityChange;
-if (typeof document.hidden !== "undefined") { // Opera 12.10 і Firefox 18 і більше пізніша підтримка
-  hidden = "hidden";
-  visibilityChange = "visibilitychange";
-} else if (typeof document.msHidden !== "undefined") {
-  hidden = "msHidden";
-  visibilityChange = "msvisibilitychange";
-} else if (typeof document.webkitHidden !== "undefined") {
-  hidden = "webkitHidden";
-  visibilityChange = "webkitvisibilitychange";
-}
-
-var videoElement = document.getElementById("videoElement");
-
-// Якщо сторінка прихована, зупиніть відео;
-// Якщо сторінка відображається, відтворіть відеозображення;
-
-function handleVisibilityChange() {
-  if (document[hidden]) {
-    videoElement.pause();
-  } else {
-    videoElement.play();
-  }
-}
-
-      // Попереджаємо, якщо браузер не підтримує addEventListener або Page Visibility API
-if (typeof document.addEventListener === "undefined" || hidden === undefined) {
-  console.log("Для цього демонстрування потрібен браузер, наприклад, Google Chrome або Firefox, який підтримує API для перегляду сторінок.");
-} else {
-      // Зміна видимості сторінки
-  document.addEventListener(visibilityChange, handleVisibilityChange, false);
-
-     // Коли відео призупиняється, встановлюємо назву.
-     // Це свідчитеме про паузу.
-  videoElement.addEventListener("pause", function(){
-      document.title = 'Paused';
-  }, false);
-
-  // Коли відео відтворюється, встановлюємо назву.
-  videoElement.addEventListener("play", function(){
-      document.title = 'Playing';
-  }, false);
-
-}
-
- -

Властивості, використані в інтерфейсі документа

- -

API Видимість сторінки додає наступні властивості до інтерфейсу {{domxref("Document")}} :

- -
-
{{domxref("Document.hidden")}} {{ReadOnlyInline}}
-
Повертає true , якщо сторінка знаходиться в стані, яке вважається прихованим для користувача, і false якщо навпаки.
-
{{domxref("Document.visibilityState")}} {{ReadOnlyInline}}
-
 {{domxref ("DOMString")}} вказує на поточний стан видимості документа. Можливі значення: -
-
visible
-
Зміст сторінки може бути, принаймні, частково видимим. На практиці це означає, що сторінка є закладкою на передньому плані немінімізірованного вікна.
-
hidden
-
Вміст сторінки не видно користувачеві або через те, що вкладка документа знаходиться в фоновому режимі, або через те, що частина вікна прихована, або через те, що екран пристрою вимкнений.
-
prerender
-
Вміст сторінки є попередніми і невидимим для користувача. Документ може буті в стані попереднього завантаження. -
Примітка: Не всі браузери підтримують попереднє завантаження.
-
-
unloaded
-
Сторінка перебуває в процесі вивантаження з пам'яті. -
Примітка: Не всі браузери підтримують це значення.
-
-
-
-
{{domxref("Document.onvisibilitychange")}}
-
 {{domxref("EventListener")}} задає код, який буде викликатися при виникненні події {{event("visibilitychange")}} .
-
- -
//startSimulation та pauseSimulation визначені в іншому місці
-function handleVisibilityChange() {
-  if (document.hidden) {
-    pauseSimulation();
-  } else  {
-    startSimulation();
-  }
-}
-
-document.addEventListener("visibilitychange", handleVisibilityChange, false);
-
- -

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

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Початкове значення.
- -

Працює з браузерами

- -
-

Document.visibilityState

- -
- - -

{{Compat("api.Document.visibilityState")}}

-
-
- -

Дивись також

- - diff --git a/files/uk/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html b/files/uk/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html new file mode 100644 index 0000000000..cb7b8b615b --- /dev/null +++ b/files/uk/web/api/canvas_api/tutorial/hit_regions_and_accessibility/index.html @@ -0,0 +1,108 @@ +--- +title: Чутливі ділянки та доступність +slug: Web/API/Canvas_API/Tutorial/Чутливі_ділянки_та_доступність +tags: + - Canvas + - Графіка + - Полотно + - Підручник +translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility +--- +
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
+ +
Власне HTML-елемент {{HTMLElement("canvas")}} являє собою лише множину кольорових точок і не містить жодних відомостей про намальовані об'єкти. Вміст полотна жодним чином не розкривається інструментам доступності, як це передбачено для семантичного HTML. Тож загалом, слід уникати використання полотен в застосунках або сайтах, від яких вимагається підтримка доступності. Проте наведені нижче настанови допоможуть все ж дещо уприступнити вміст полотен.
+ +

Запасний вміст

+ +

Вміст між тегами <canvas> … </canvas> може відігравати роль запасного варіанту для тих {{glossary("Browser", "переглядачів")}}, що не мають підтримки полотен. Він також вельми корисний тоді, коли користувач потребує допоміжних засобів (як-от екранний диктор), які можуть читати дерево DOM всередині. Чудовий приклад з html5accessibility.com показує, як це можна здійснити:

+ +
<canvas>
+  <h2>Shapes</h2>
+  <p>A rectangle with a black border.
+   In the background is a pink circle.
+   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
+   Partially overlaying the circle is a green
+   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
+   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
+   both of which are semi-opaque, so the full circle can be seen underneath.</p>
+</canvas> 
+ +

Перегляньте відео від Стіва Фолкнера про те, як екранний диктор NVDA читає цей приклад.

+ +

Правила ARIA

+ +

Accessible Rich Internet Applications (ARIA) визначає способи того, як зробити веб-застосунки та вміст доступнішими для людей з певними вадами. Можна вжити ARIA-атрибути для описання поведінки й призначення HTML-елемента полотна:

+ +
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
+
+ +

Дивіться ARIA та Використання ARIA, щоб дізнатись більше.

+ +

Чутливі ділянки

+ +

Однією з поширених задач є з'ясування того, чи належать координати миші до певної ділянки на полотні. Відповідний API уможливлює створення певних чутливих ділянок на полотні та дає інші можливості розкрити взаємодіяльний вміст полотна інструментам доступності. Він дозволяє полегшити виявлення влучень (належності координат миші певній ділянці) та доправити відповідні події до елементів DOM. Цей API має такі три методи (досі лишаються дослідними в сучасних переглядачах, тож перевіряйте таблиці сумісності):

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
Створює чутливу ділянку на полотні.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
Видаляє з полотна чутливу ділянку із зазначеним id .
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
Видаляє з полотна всі чутливі ділянки.
+
+ +

Створюючи новий контур з допомогою {{domxref("CanvasRenderingContext2D.beginPath()")}} можна перетворити його на чутливу ділянку, а тоді, перевіряючи значення властивості {{domxref("MouseEvent.region")}}, з'ясовувати, чи влучає миша у вказану область:

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: 'circle'});
+
+canvas.addEventListener('mousemove', function(event) {
+  if (event.region) {
+    console.log('Влучив у ділянку: ' + event.region);  // Влучив у ділянку: circle
+  }
+});
+
+ +

Крім того, метод addHitRegion() може також приймати параметр control, що вказує елемент (має бути нащадком елемента canvas), до якого доправлятимуться події:

+ +
ctx.addHitRegion({control: element});
+ +

Наприклад, це може стати в нагоді для доправлення подій до елементів {{HTMLElement("input")}}.

+ +

Облямівки фокуса

+ +

Для роботи з клавіатури, облямівки фокуса є зручними індикаторами, що полегшують пересування сторінкою. Щоб намалювати облямівку фокуса навколо малюнка (контура) на полотні, можна скористатися методом drawFocusIfNeeded().

+ +
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
+
Якщо відповідний елемент перебуває у фокусі, цей метод намалює облямівку навколо контура.
+
+ +

Крім того, можна використати метод scrollPathIntoView(), щоб зробити елемент видимим на екрані, якщо він перебуває у фокусі, наприклад.

+ +
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
+
Гортає поточний чи вказаний контур до видимої області.
+
+ +

Див. також

+ + + +
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git "a/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" "b/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" deleted file mode 100644 index cb7b8b615b..0000000000 --- "a/files/uk/web/api/canvas_api/tutorial/\321\207\321\203\321\202\320\273\320\270\320\262\321\226_\320\264\321\226\320\273\321\217\320\275\320\272\320\270_\321\202\320\260_\320\264\320\276\321\201\321\202\321\203\320\277\320\275\321\226\321\201\321\202\321\214/index.html" +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Чутливі ділянки та доступність -slug: Web/API/Canvas_API/Tutorial/Чутливі_ділянки_та_доступність -tags: - - Canvas - - Графіка - - Полотно - - Підручник -translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility ---- -
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
- -
Власне HTML-елемент {{HTMLElement("canvas")}} являє собою лише множину кольорових точок і не містить жодних відомостей про намальовані об'єкти. Вміст полотна жодним чином не розкривається інструментам доступності, як це передбачено для семантичного HTML. Тож загалом, слід уникати використання полотен в застосунках або сайтах, від яких вимагається підтримка доступності. Проте наведені нижче настанови допоможуть все ж дещо уприступнити вміст полотен.
- -

Запасний вміст

- -

Вміст між тегами <canvas> … </canvas> може відігравати роль запасного варіанту для тих {{glossary("Browser", "переглядачів")}}, що не мають підтримки полотен. Він також вельми корисний тоді, коли користувач потребує допоміжних засобів (як-от екранний диктор), які можуть читати дерево DOM всередині. Чудовий приклад з html5accessibility.com показує, як це можна здійснити:

- -
<canvas>
-  <h2>Shapes</h2>
-  <p>A rectangle with a black border.
-   In the background is a pink circle.
-   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
-   Partially overlaying the circle is a green
-   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
-   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
-   both of which are semi-opaque, so the full circle can be seen underneath.</p>
-</canvas> 
- -

Перегляньте відео від Стіва Фолкнера про те, як екранний диктор NVDA читає цей приклад.

- -

Правила ARIA

- -

Accessible Rich Internet Applications (ARIA) визначає способи того, як зробити веб-застосунки та вміст доступнішими для людей з певними вадами. Можна вжити ARIA-атрибути для описання поведінки й призначення HTML-елемента полотна:

- -
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
-
- -

Дивіться ARIA та Використання ARIA, щоб дізнатись більше.

- -

Чутливі ділянки

- -

Однією з поширених задач є з'ясування того, чи належать координати миші до певної ділянки на полотні. Відповідний API уможливлює створення певних чутливих ділянок на полотні та дає інші можливості розкрити взаємодіяльний вміст полотна інструментам доступності. Він дозволяє полегшити виявлення влучень (належності координат миші певній ділянці) та доправити відповідні події до елементів DOM. Цей API має такі три методи (досі лишаються дослідними в сучасних переглядачах, тож перевіряйте таблиці сумісності):

- -
-
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
-
Створює чутливу ділянку на полотні.
-
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
-
Видаляє з полотна чутливу ділянку із зазначеним id .
-
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
-
Видаляє з полотна всі чутливі ділянки.
-
- -

Створюючи новий контур з допомогою {{domxref("CanvasRenderingContext2D.beginPath()")}} можна перетворити його на чутливу ділянку, а тоді, перевіряючи значення властивості {{domxref("MouseEvent.region")}}, з'ясовувати, чи влучає миша у вказану область:

- -

HTML

- -
<canvas id="canvas"></canvas>
- -

JavaScript

- -
var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.beginPath();
-ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
-ctx.fill();
-ctx.addHitRegion({id: 'circle'});
-
-canvas.addEventListener('mousemove', function(event) {
-  if (event.region) {
-    console.log('Влучив у ділянку: ' + event.region);  // Влучив у ділянку: circle
-  }
-});
-
- -

Крім того, метод addHitRegion() може також приймати параметр control, що вказує елемент (має бути нащадком елемента canvas), до якого доправлятимуться події:

- -
ctx.addHitRegion({control: element});
- -

Наприклад, це може стати в нагоді для доправлення подій до елементів {{HTMLElement("input")}}.

- -

Облямівки фокуса

- -

Для роботи з клавіатури, облямівки фокуса є зручними індикаторами, що полегшують пересування сторінкою. Щоб намалювати облямівку фокуса навколо малюнка (контура) на полотні, можна скористатися методом drawFocusIfNeeded().

- -
-
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
-
Якщо відповідний елемент перебуває у фокусі, цей метод намалює облямівку навколо контура.
-
- -

Крім того, можна використати метод scrollPathIntoView(), щоб зробити елемент видимим на екрані, якщо він перебуває у фокусі, наприклад.

- -
-
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
-
Гортає поточний чи вказаний контур до видимої області.
-
- -

Див. також

- - - -
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/uk/web/api/event/index.html b/files/uk/web/api/event/index.html new file mode 100644 index 0000000000..e1aab3dfde --- /dev/null +++ b/files/uk/web/api/event/index.html @@ -0,0 +1,188 @@ +--- +title: Подія +slug: Web/API/Подія +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

Event інтерфейс представляє подію, що відбувається в DOM. Подія може бути ініційована дією користувача, наприклад, кліком мишки або натисканням клавіши на клавіатурі, або згенерована API, щоб показати прогрес асинхронного завдання, тощо. Це може бути також ініційовано програмно викликом HTMLElement.click() методу елемента, або створенням екземпляру події, потім відправленням його до вказаного цільового елементу, використовуючи EventTarget.dispatchEvent().

+ +

Існує багато різновидів подій, деякі з котрих використовують інші інтерфейси, основані на головному інтерфейсі Event. Сам по собі Event вміщає можливості та методи, спільні для всіх подій.

+ +

Багато елементів DOM можуть бути налаштовані прийняти (або "почути") ці події та виконати код у відповідь на процес їхньої обробки. Хендлери подій звичайно пов'язані або додаються до різноманітних HTML elements (таких як <button><div>, <span>, і т.п.) при використанні EventTarget.addEventListener(), а це, як правило, замінює використання атрибутів хендлера подій старого HTML. Надалі за необхідності додавання, такі хендлери також можна відключати, якщо потрібно, використовуючи removeEventListener().  

+ +

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

+ +

Коли є багато вкладених елементів, кожний зі своїм особистим хендлером (хендлерами), обробка подій може стати дуже складною - особливо там, де батьківський елемент отримує ту ж саму подію, що й її дочірній елемент, тому що "просторово" вони перетинаються і таким чином подія технічно з'являється в них обох, а порядок обробки таких подій залежить від параметрів вспливаючих подій та захоплення кожного обробника.

+ +

Інтерфейси на основі Event

+ +

Нижче надано список інтерфейсів, які існують на основі головного Event інтерфейсу, із ссилками на відповідну документацію в довіднику MDN API.

+ +

Зверніть увагу, що всі інтерфейси подій мають назви із закінченням "Event".

+ + + +
+ +
+ +

Конструктор

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Створює  Event об'єкт та повертає його абоненту.
+
+ +

Властивості

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
Булевий вираз вказує на те, чи вспливає подія через DOM.
+
{{domxref("Event.cancelBubble")}}
+
Історичний псевдонім {{domxref("Event.stopPropagation()")}}. Встановлення його значення true  перед поверненням з обробника події запобігає поширенню події.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
Булевий вираз вказує на те, чи скасовується подія.
+
{{domxref("Event.composed")}} {{ReadOnlyInline}}
+
Булевий вираз вказує на те, чи може подія всплити через межу між  тінню DOM та черговим DOM.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
Посилання на зареєстровану зараз ціль події. Це об'єкт, на котрий наразі планується відіслати подію. Можливо, це змінилося по дорозі через retargeting.
+
{{domxref("Event.deepPath")}} {{non-standard_inline}}
+
 {{jsxref("Array")}} of DOM {{domxref("Node")}}, через який всплила подія.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Вказує, чи виклик {{domxref("event.preventDefault()")}}  скасував подію.
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Вказує, яка фаза потоку подій обробляється.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Явна оригінальна мета події (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
Початкова ціль події перед будь-якими ретаргетингами. (Mozilla-specific).
+
{{domxref("Event.returnValue")}}
+
Історична властивість, представлена Internet Explorer і згодом прийнята в специфікацію DOM для того, щоб забезпечити продовження  роботи існуючих сайтів. В ідеалі, вам слід спробувати використати {{domxref(''Event.preventDefault()")}} та {{domxref("Event.defaultPrevented")}} замість нього, але ви можете використовувати returnValue, якщо ви  вирішите це зробити.
+
{{domxref("Event.returnValue")}} {{non-standard_inline}}
+
Нестандартний псевдонім (зі старої версії Microsoft Internet Explorer) для {{domxref("Event.target")}}. Деякі інші браузери починають підтримувати його для веб-сумісності.
+
{{domxref("Event.target")}} {{readonlyinline}}
+
Посилання на ціль, до якої спочатку була відправлена подія.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
Час, коли було створено подію (в мілісекундах).  За специфікацією, це значення - час з епохи - але насправді визначення браузерів різняться.Крім того, ведеться робота, щоб змінити його на {{domxref("DOMHighResTimeStamp")}} .
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Вказує, чи  була подія ініційована браузером (наприклад, після натискання клавіши на клавіатурі користувачем) або за сценарієм (використовуючи метод створення подій, наприклад {{domxref("Event.initEvent")}}).
+
Застарілі властивості
+
+ +

{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}

+ +

Застарілі; використовуйте замість них {{domxref("Event.composed", "composed")}}. ({{jsxref("Boolean")}} вказує, чи вспливе дана подія через тіньовий корінь у стандарт DOM.)

+ +

Методи

+ +
+
{{domxref("Event.createEvent()")}} {{deprecated_inline}}
+
Створює нову подію, котра повинна бути ініційована викликом її  initEvent() методу.
+
{{domxref("Event.composedPath()")}}
+
Повертає шлях події (об'єкти, на які слухачі будуть викликані). Це не включає вузли через тіньові дерева, якщо тіньовий корінь було створено із закритим {{domxref("ShadowRootmode")}}.
+
{{domxref("Event.preventDefault()")}}
+
Скасовує подію, (якщо її можливо скасувати).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
Для цієї конкретної події не дозволяйте викликати всіх інших слухачів. Сюди входять слухачі, приєднані до одного й того ж елемента, а також ті, що додаються до елементів, які буде прищеплено пізніше (наприклад, під час фази введення).
+
{{domxref("Event.stopPropagation()")}}
+
Зупиняє розповсюдження подій далі у DOM.
+
Застарілі методи
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Нестандартний. Використовуйте замість нього {{domxref("Event.defaultPrevented")}}.  (Повертає значення {{domxref("Event.defaultPrevented")}}.)
+
{{domxref("Event.preventBubble()"}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Застарілий; використовуйте замість нього {{domxref("event.stopPropagation")}}. (Захищає подію від вспливання).
+
{{domxref("Event.preventcapture()"}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Застарілий; використовуйте замість нього {{domxref("event.stopPropagation"}}.
+
+ +

Технічні характеристики

+ + + + + + + + + + + + + + +
ХарактеристикаСтатусКоментар
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}}
+ +

Сумісність з браузером

+ +

приховано

+ +

Таблиця сумісності на цій сторінці формується із структурованих даних. Якщо ви захочете побачити її, будь ласка, перевірте та відправте нам запит https://github/com/mdn/browser-compat-data

+ + + +

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

+ + diff --git a/files/uk/web/api/event/target/index.html b/files/uk/web/api/event/target/index.html new file mode 100644 index 0000000000..20c17f2d31 --- /dev/null +++ b/files/uk/web/api/event/target/index.html @@ -0,0 +1,134 @@ +--- +title: Event.target +slug: Web/API/Подія/target +translation_of: Web/API/Event/target +--- +

{{ApiRef("DOM")}}

+ +

Властивість target інтерфейсу {{domxref("Event")}} є посиланням на об'єкт який відправив подію. Він відрізняється від {{domxref("Event.currentTarget")}} коли обробник події викликається в фазі спливання або фіксації події.

+ +

Синтаксис

+ +
var theTarget = event.target;
+ +

Приклад

+ +

Властивість event.target може бути використана для реалізації делегування події.

+ +
// Зробити список
+var ul = document.createElement('ul');
+document.body.appendChild(ul);
+
+var li1 = document.createElement('li');
+var li2 = document.createElement('li');
+ul.appendChild(li1);
+ul.appendChild(li2);
+
+function hide(e){
+  // e.target вказує на елемент <li> на якому було натиснуто
+  // Це відрізняється від e.currentTarget який буде посилатися на батьківський <ul> в даному контексті
+  e.target.style.visibility = 'hidden';
+}
+
+// Приєднання слухача подій до списка
+// Він запуститься при натисканні кожного <li>
+ul.addEventListener('click', hide, false);
+
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

Сумісність з браузерами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Нотатки про сумісність

+ +

В браузерах IE 6-8 використовується інша модель подій. Слухачі подій приєднуються з використанням нестандартного методу {{domxref('EventTarget.attachEvent')}}. В цій моделі, об'єкт події має {{domxref('Event.srcElement')}} властивість, замість властивості target, і воно має ту ж саму семантику як event.target.

+ +
function hide(e) {
+  // Підтримка IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

Читати також

+ + diff --git a/files/uk/web/api/htmlmediaelement/abort_event/index.html b/files/uk/web/api/htmlmediaelement/abort_event/index.html new file mode 100644 index 0000000000..40a9e144fc --- /dev/null +++ b/files/uk/web/api/htmlmediaelement/abort_event/index.html @@ -0,0 +1,68 @@ +--- +title: abort +slug: Web/Events/abort +translation_of: Web/API/HTMLMediaElement/abort_event +translation_of_original: Web/Events/abort +--- +

Подія abort спрацьовує коли завантаження ресурсу було перервано.

+ +

Загальна інформація

+ +
+
Специфікація
+
DOM L3
+
Interface
+
UIEvent if generated from a user interface, Event otherwise.
+
Bubbles
+
No
+
Cancelable
+
No
+
Target
+
Element
+
Default Action
+
None
+
+ +

Властивості

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
diff --git a/files/uk/web/api/page_visibility_api/index.html b/files/uk/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..6675a3783b --- /dev/null +++ b/files/uk/web/api/page_visibility_api/index.html @@ -0,0 +1,201 @@ +--- +title: API відображення сторінки +slug: Web/API/API_відображення_сторінки +tags: + - API + - API відображення сторінки + - visibilityState + - visibilitychange + - відображення сторінки + - процеси скритої закладки + - фоновий режим +translation_of: Web/API/Page_Visibility_API +--- +
{{DefaultAPISidebar("Page Visibility API")}}
+ +
+ +

При перегляді сайту за допомогою вкладок існує ймовірність того, що будь-яка з веб-сторінок знаходиться в фоновому режимі і тому користувач її не бачить. API відображення сторінки надає події, які ви можете відстежити, щоб дізнатися, коли документ стає видимим або прихованим, а також дозволяє отримати поточний стан прихованості/видимості сторінки.

+ +
+

Примітка: API відображення сторінки є особливо корисним для економії ресурсів та підвищення продуктивності, дозволяючи сторінці уникнути виконання непотрібних завдань, коли документ не є видимим.

+
+ +

Коли користувач згортає вікно або перемикається на іншу вкладку, API посилає подію {{event("visibilitychange")}}, щоб передати слухачам інформацію про зміну стану сторінки. Ви можете виявити подію і виконати деякі дії або нічого не виконувати. Наприклад, якщо ваш веб-додаток програє відео, він може поставити відео на паузу, коли користувач переміщує вкладку у фоновий режим, і відновити відтворення, коли користувач повернеться до цієї вкладки. Користувач не втрачає миті у відео, звук відео не заважає аудіо в новій вкладці на передньому плані, і користувач не пропустить жодного моменту в них.

+ +

Стан видимості {{HTMLElement ("iframe")}} збігаються зі станом батьківського документа. Приховування <iframe> за допомогою властивостей CSS (таких як {{cssxref ("display", "display: none;")}}) не викликає подій видимості і не змінює стан документа, що міститься в кадрі.

+ +

Випадки використання

+ +

Розглянемо декілька прикладів використання API видимості сторінки.

+ + + +

Розробники у минулому використовували недосконалі проксі для виявлення цього. Наприклад, перегляд {{event("blur")}} і {{event("focus")}} подій на вікні допомагає зрозуміти, коли ваша сторінка не є активною, але не говорить про те, що ваша сторінка насправді прихована для користувача. API Видимість сторінки вирішує цю проблему.

+ +
+

Примітка: У той час як {{domxref ("GlobalEventHandlers.onblur", "onblur")}} та {{domxref ("GlobalEventHandlers.onfocus", "onfocus")}} скажуть вам, коли користувач перемикає вікно, але це не обов'язково означає, що воно приховано. Сторінки стають прихованими тільки тоді, коли користувач перемикає вкладки або згортає вікно браузера, що містить вкладку.

+
+ +

Політика позиціонування, як сприяння продуктивності фонової сторінки

+ +

Окремо від API відображення сторінки агенти  користувача зазвичай мають ряд власних політик для зниження впливу продуктивності фонових або прихованих вкладок. Вони можуть включати в себе:

+ + + +

Деякі процеси виключені з цього гасящего режиму. У цих випадках ви також можете використовувати API видимості сторінки, щоб зменшити вплив на продуктивність.

+ + + +

Приклад

+ +

Подивіться живий приклад (відео зі звуком).

+ +

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

+ +
   // Встановіть ім'я властивості hidden і події зміни для видимості.
+
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Opera 12.10 і Firefox 18 і більше пізніша підтримка
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.msHidden !== "undefined") {
+  hidden = "msHidden";
+  visibilityChange = "msvisibilitychange";
+} else if (typeof document.webkitHidden !== "undefined") {
+  hidden = "webkitHidden";
+  visibilityChange = "webkitvisibilitychange";
+}
+
+var videoElement = document.getElementById("videoElement");
+
+// Якщо сторінка прихована, зупиніть відео;
+// Якщо сторінка відображається, відтворіть відеозображення;
+
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+      // Попереджаємо, якщо браузер не підтримує addEventListener або Page Visibility API
+if (typeof document.addEventListener === "undefined" || hidden === undefined) {
+  console.log("Для цього демонстрування потрібен браузер, наприклад, Google Chrome або Firefox, який підтримує API для перегляду сторінок.");
+} else {
+      // Зміна видимості сторінки
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+     // Коли відео призупиняється, встановлюємо назву.
+     // Це свідчитеме про паузу.
+  videoElement.addEventListener("pause", function(){
+      document.title = 'Paused';
+  }, false);
+
+  // Коли відео відтворюється, встановлюємо назву.
+  videoElement.addEventListener("play", function(){
+      document.title = 'Playing';
+  }, false);
+
+}
+
+ +

Властивості, використані в інтерфейсі документа

+ +

API Видимість сторінки додає наступні властивості до інтерфейсу {{domxref("Document")}} :

+ +
+
{{domxref("Document.hidden")}} {{ReadOnlyInline}}
+
Повертає true , якщо сторінка знаходиться в стані, яке вважається прихованим для користувача, і false якщо навпаки.
+
{{domxref("Document.visibilityState")}} {{ReadOnlyInline}}
+
 {{domxref ("DOMString")}} вказує на поточний стан видимості документа. Можливі значення: +
+
visible
+
Зміст сторінки може бути, принаймні, частково видимим. На практиці це означає, що сторінка є закладкою на передньому плані немінімізірованного вікна.
+
hidden
+
Вміст сторінки не видно користувачеві або через те, що вкладка документа знаходиться в фоновому режимі, або через те, що частина вікна прихована, або через те, що екран пристрою вимкнений.
+
prerender
+
Вміст сторінки є попередніми і невидимим для користувача. Документ може буті в стані попереднього завантаження. +
Примітка: Не всі браузери підтримують попереднє завантаження.
+
+
unloaded
+
Сторінка перебуває в процесі вивантаження з пам'яті. +
Примітка: Не всі браузери підтримують це значення.
+
+
+
+
{{domxref("Document.onvisibilitychange")}}
+
 {{domxref("EventListener")}} задає код, який буде викликатися при виникненні події {{event("visibilitychange")}} .
+
+ +
//startSimulation та pauseSimulation визначені в іншому місці
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

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

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Початкове значення.
+ +

Працює з браузерами

+ +
+

Document.visibilityState

+ +
+ + +

{{Compat("api.Document.visibilityState")}}

+
+
+ +

Дивись також

+ + diff --git a/files/uk/web/api/window/domcontentloaded_event/index.html b/files/uk/web/api/window/domcontentloaded_event/index.html new file mode 100644 index 0000000000..96ca54cfb0 --- /dev/null +++ b/files/uk/web/api/window/domcontentloaded_event/index.html @@ -0,0 +1,152 @@ +--- +title: DOMContentLoaded +slug: Web/Events/DOMContentLoaded +translation_of: Web/API/Window/DOMContentLoaded_event +--- +

Подія DOMContentLoaded викликається, коли вихідний HTML документ повністю завантажився та був розібраний (parse), без очікування повного завантаження стилів, зображень, сабфреймів (subframes). Зовсім інша подія - load - має використовуватися лише для того, щоб визначити повне завантаження сторінки. Використання load там, де застосування DOMContentLoaded є більш доречним, є дуже поширеною помилкою, тому будьте уважними.

+ +

{{Note("Синхронний Javascript затримує парсинг DOM.")}}

+ +

{{Note("Існує безліч універсальних та автономних бібліотек, які  попонують кроссбраузерні методи для визначення готовності DOM.")}}

+ +

Прискорення

+ +

Якщо ви хочете, щоб DOM був розібраним (got parsed) якомога швидше після того, як користувач зробив запит сторінки, ви можете зробити ваш JavaScript асинхронним та оптимізувати завантаження стилів. Якщо цього не зробити, це сповільнить завантаження сторінки через те, що воно буде відбуватися паралельно і марнувати трафік у головного html документа.

+ +

Основна інформація

+ +
+
Специфікація
+
HTML5
+
Інтерфейс
+
Подія
+
Спливання
+
Так
+
Можливість скасування
+
Так (однак скасування як простої події скасувати не можна)
+
 
+
 
+
 
+
 
+
Ціль
+
Документ
+
Типова дія
+
Немає.
+
+ +

Властивості

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ВластивістьТипОпис
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
+ +

Приклад

+ +
<script>
+  document.addEventListener("DOMContentLoaded", function(event) {
+    console.log("DOM fully loaded and parsed");
+  });
+</script>
+
+ +
<script>
+  document.addEventListener("DOMContentLoaded", function(event) {
+    console.log("DOM fully loaded and parsed");
+  });
+
+for(var i=0; i<1000000000; i++)
+{} // this synchronous script is going to delay parsing of the DOM. So the DOMContentLoaded event is going to launch later.
+</script>
+
+ +

Сумісність з браузерами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0[1]{{CompatGeckoDesktop("1")}}[1]9.0[2]9.03.1[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile("1")}}[1]{{CompatUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +

[1] Bubbling для цієї події підтримується принаймні Gecko 1.9.2, Chrome 6, and Safari 4.

+ +

[2] Internet Explorer 8 підтримує подію readystatechange , яка може використовуватися для того, щоб визначити чи готовий DOM. У більш ранніх версіях Internet Explorer цей стан може бути визначений повторними спробами виконання document.documentElement.doScroll("left");,  так як цей фрагмент коду буде генерувати помилку, поки DOM не буде готовий.

+ +

Подібні події

+ + diff --git a/files/uk/web/api/windoworworkerglobalscope/settimeout/index.html b/files/uk/web/api/windoworworkerglobalscope/settimeout/index.html new file mode 100644 index 0000000000..19c90148ce --- /dev/null +++ b/files/uk/web/api/windoworworkerglobalscope/settimeout/index.html @@ -0,0 +1,428 @@ +--- +title: WindowTimers.setTimeout() +slug: Web/API/WindowTimers/setTimeout +translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +
Метод setTimeout(), що належить об'єкту {{domxref("WindowOrWorkerGlobalScope")}}, та наслідується від window.setTimeout,  встановлює таймер, що виконує функцію або вказаний фрагмент коду один раз, щойно спливе заданий час.
+ +
 
+ +

Синтаксис

+ +
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
+var timeoutID = window.setTimeout(code[, delay]);
+
+ +

Параметри

+ +
+
func
+
{{jsxref("function")}} котру необхідно виконати після того, як вийде заданий час.
+
code
+
Опційний синтаксис, котрий дозволяє задавати рядок замість функції, котра компілюється і виконується при спрацюванні таймера. Використання цього синтаксису не рекомендовано з тих же ж причин, котрі роблять застосування {{jsxref("eval()")}} загрозою безпеці.
+
delay {{optional_inline}}
+
 
+
Час у мілісекундах (тисячних секунди), котрий таймер має зачекати перед тим, як виконати вказану функцію або код. Якщо цей параметр пропустити, буде використано значення 0. Варто зазначити, що справжній час затримки, може бути довшим. Дивіться розділ {{anch("Reasons for delays longer than specified","Причини, з яких затримка є фактично довшою ніж задано")}}
+
param1, ..., paramN {{optional_inline}}
+
Додаткові параметри, що передаються до func або code, щойно час таймера спливе.
+
+ +
+

Зверніть увагу:  Internet Explorer 9 та більш ранні версії не підтримують додаткові параметри. Застосовуйте поліфіл, щобл уможливити цей функціонал (див. розділ Callback arguments).  

+
+ +

Значення, що повертається

+ +


+ Після виклику setTimeout(), повертається timeoutID  - це не нульове цифрове значення, що використовується для ідентифікації створеного таймера. Цей ідентифікатор можна передати як параметр до {{domxref("Window.clearTimeout()")}} щоб відмінити таймер.

+ +

Корисно знати, що setTimeout() та {{domxref("WindowTimers.setInterval", "setInterval()")}} використовують спільну колекцію ID ідентифікаторів, а також що  clearTimeout() та {{domxref("WindowTimers.clearInterval", "clearInterval()")}} технічно можуть бути взаємозамінними. Тим не менше, задля ясності, варто завжди зіставляти їх, аби не допускати помилок під час розробки коду. 

+ +

Приклад

+ +

У наступному прикладі створено дві кнопки на веб сторінці, що прив'язані до setTimeout() та clearTimeout() процесів. Після натискання на першу кнопку встановлюється таймер, що викликає діалогове вікно alert через дві секунди та зберігає ID таймера для подальшого використання у clearTimeout(). За бажанням ви можете відмінити цей таймер, якщо натисните другу кнопку.

+ +

HTML код

+ +
<p>Live Example</p>
+<button onclick="delayedAlert();">Відобразити діалогове вікно alert через дві секунди.</button>
+<p></p>
+<button onclick="clearAlert();">Відмінити відображення діалогового вікна.</button>
+
+ +

JavaScript код

+ +
var timeoutID;
+
+function delayedAlert() {
+  timeoutID = window.setTimeout(slowAlert, 2000);
+}
+
+function slowAlert() {
+  alert("Це було дійсно повільно!");
+}
+
+function clearAlert() {
+  window.clearTimeout(timeoutID);
+}
+
+ +

Результат

+ +

{{EmbedLiveSample('Example', 'Приклад')}}

+ +

Дивіться також clearTimeout() example.

+ +

Поліфіл

+ +

Якщо вам необхідно передати один чи декілька аргументів до колбек функції, а також потрібно, щоб цей функціонал працював у браузерах, що не підтримують передачу додаткових аргументів для setTimeout() чи setInterval() (наприклад, версії Internet Explorer 9 чи нижче), ви можете застосувати цей поліфіл, який активує стандартну HTML5 функціональність. Просто додайте цей код на початку вашого скрипта: 

+ +
/*\
+|*|
+|*|  Polyfill which enables the passage of arbitrary arguments to the
+|*|  callback functions of JavaScript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+(function() {
+  setTimeout(function(arg1) {
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeST__ = window.setTimeout;
+    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeST__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+
+  var interval = setInterval(function(arg1) {
+    clearInterval(interval);
+    if (arg1 === 'test') {
+      // feature test is passed, no need for polyfill
+      return;
+    }
+    var __nativeSI__ = window.setInterval;
+    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
+      var aArgs = Array.prototype.slice.call(arguments, 2);
+      return __nativeSI__(vCallback instanceof Function ? function() {
+        vCallback.apply(null, aArgs);
+      } : vCallback, nDelay);
+    };
+  }, 0, 'test');
+}())
+
+ +

Фікс для IE

+ +

Якщо вам потрібен фікс, який не впливатиме на роботу жодного іншого мобільного чи десктопного браузера, окрім IE9 та нижче, ви можете скористатись умовними коментарями JavaScript:

+ +
/*@cc_on
+  // conditional IE < 9 only fix
+  @if (@_jscript_version <= 9)
+  (function(f){
+     window.setTimeout=f(window.setTimeout);
+     window.setInterval=f(window.setInterval);
+  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
+  @end
+@*/
+
+ +

Або використати умовні коментарі HTML для IE9 та нижче:

+ +
<!--[if lte IE 9]><script>
+(function(f){
+window.setTimeout=f(window.setTimeout);
+window.setInterval=f(window.setInterval);
+})(function(f){return function(c,t){
+var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
+});
+</script><![endif]-->
+
+ +

Тимчасові рішення

+ +

Ще одне можливе рішення - використання анонімної функції для виклику колбека, але це вартісне рішення. Приклад:

+ +
var intervalID = setTimeout(function() { myFunc("one", "two", "three"); }, 1000);
+
+ +

Приклад, наведений вище, може бути також написаний за допомогою   arrow function:

+ +
var intervalID = setTimeout(() => { myFunc("one", "two", "three"); }, 1000);
+
+ +

Ще одне рішення - використання   function's bind. Приклад:

+ +
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
+
+ +

Проблема "this"

+ +

Коли ви передаєте до setTimeout() метод або будь-яку іншу функцію, ймовірно вона буде викликана не з тим значенням this, на яке ви очікуєте. Ця проблема детально описана у JavaScript reference.

+ +

Пояснення

+ +

Код, що виконується всередині setTimeout(), викликається із  іншого контекста виконання (execution context), ніж у функції, яка викликала setTimeout. До функції, яку викликають всередині setTimeout застосовуються звичайні правила призначення this. І, якщо ви не встановили this під час виклику або за допомогою bind, його значенням за замовчуванням буде об'єкт  global (або window) у нестрогому режимі, або undefined у строгому режимі. Значення this буде іншим, аніж у функції, яка викликала setTimeout. Розгляньте наступний приклад:

+ +
myArray = ["zero", "one", "two"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+ +

Приклад вище працює тому, що myMethod викликано, як метод масиву myArray. Тому його this дорівнює myArray, а значення this[sProperty] всередині метода дорівнює myArray[sProperty]. Тим не менше, у наступному прикладі:

+ +
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
+ +

Метод myArray.myMethod передано до setTimeout, як звичайну функцію, якій не задано значення this. І коли вона викликається, її this за замовчуванням дорівнює об'єкту window. У  setTimeout неможливо передати this аргументом, як, наприклад, у методи Array (forEach, reduce, тощо), або через використання  call, як показано у прикладі нижче:

+ +
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+
+ +

Можливі рішення

+ +

Типовий спосіб вирішення цієї проблеми - використання функції обгортки, яка встановлює this із необхідним значенням: 

+ +
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

Стрілочна функція також є прийнятною альтернативою:

+ +
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
+ +

Ще одне можливе рішення проблеми this - замінити нативні глобальні функції setTimeout() та setInterval() кастомними функціями, які можуть приймати об'єкт this і застосовувати його у колбек функції, використовуючи  Function.prototype.call. Наприклад: 

+ +
// Enable setting 'this' in JavaScript timers
+
+var __nativeST__ = window.setTimeout,
+    __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this,
+      aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this,
+      aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
Зверніть увагу:  Подібний підхід дозволяє передавати будь-яку кількість аргументів у колбек функцію таймерів навіть для IE. Таким чином, цей спосіб може також бути використаний як поліфіл. Перегляньте параграф Callback arguments .
+ +

Випробування нового підхода:

+ +
myArray = ["zero", "one", "two"];
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2.5 seconds
+
+ +
Зверніть увагу:  JavaScript 1.8.5 впровадив метод   Function.prototype.bind(), який встановлює значення this для кожного виклику вказаної функції. Це допомагає уникнути використання функції обгортки для призначення this колбека.
+ +

Приклад використання bind():

+ +
myArray = ["zero", "one", "two"];
+myBoundMethod = (function (sProperty) {
+    console.log(arguments.length > 0 ? this[sProperty] : this);
+}).bind(myArray);
+
+myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
+myBoundMethod(1); // prints "one"
+setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
+setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
+
+ +

Примітки

+ +

Таймер можна скасувати за допомогою {{domxref("Window.clearTimeout()")}}. Щоб викликати функцію повторно (наприклад, через кожні N мілісекунди), використовуйте  {{domxref("Window.setInterval()")}}.

+ +

Важливо пам'ятати, що функція або фрагмент коду не можуть бути виконані, допоки не буде завершено поток функції, яка викликала setTimeout(). Наприклад. 

+ +
function foo(){
+  console.log('foo has been called');
+}
+setTimeout(foo, 0);
+console.log('After setTimeout');
+ +

Виведе в консоль:

+ +
After setTimeout
+foo has been called
+ +

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

+ +

Passing string literals

+ +

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

+ +
// Recommended
+window.setTimeout(function() {
+    alert("Hello World!");
+}, 500);
+
+// Not recommended
+window.setTimeout("alert('Hello World!');", 500);
+
+ +

A string passed to setTimeout is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

+ +

Причини чому затримка є фактично довшою ніж вказано

+ +

There are a number of reasons why a timeout may take longer to fire than anticipated. This section describes the most common reasons.

+ +

Nested timeouts forced to >=4ms

+ +

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5.

+ +

In fact, 4 ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{geckoRelease("5.0")}}, the minimum timeout value for nested timeouts was 10 ms.

+ +

To implement a 0 ms timeout in a modern browser, you can use {{domxref("window.postMessage()")}} as described here.

+ +

Timeouts in inactive tabs clamped to >=1000ms

+ +

To reduce the load (and associated battery usage) from background tabs, timeouts are often clamped to firing no more often than once per second (1000 ms) in inactive tabs.

+ +

Firefox implements this behavior since version 5 (see {{bug(633421)}}, the 1000ms constant can be tweaked through the dom.min_background_timeout_value preference). Chrome implements this behavior since version 11 (crbug.com/66078).

+ +

Firefox for Android uses a timeout value of 15 minutes for background tabs since {{bug(736602)}} in Firefox 14, and background tabs can also be unloaded entirely.

+ +
+

Firefox 50 no longer throttles background tabs if a Web Audio API {{domxref("AudioContext")}} is actively playing sound. Firefox 51 further amends this such that background tabs are no longer throttled if an {{domxref("AudioContext")}} is present in the tab at all, even if no sound is being played. These resolve a number of issues with apps which play note-based music not being able to time or synchronize the music properly when the tab is in the background.

+
+ +

Late timeouts

+ +

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks

+ +

Maximum delay value

+ +

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1")}}4.04.01.0
Supports parameters for callback[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.01.0{{CompatGeckoMobile("1")}}6.06.01.0
Supports parameters for callback[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Whether it supports the optional parameters when in its first form or not.

+ +

See also

+ + diff --git a/files/uk/web/api/windowtimers/index.html b/files/uk/web/api/windowtimers/index.html deleted file mode 100644 index d28752bde7..0000000000 --- a/files/uk/web/api/windowtimers/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: WindowTimers -slug: Web/API/WindowTimers -tags: - - API - - HTML DOM - - Interface - - Intervals - - Mixin - - NeedsTranslation - - Reference - - Timers - - TopicStub - - Workers -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowTimers ---- -
{{APIRef("HTML DOM")}}
- -

WindowTimers is a mixin used to provide utility methods which set and clear timers. No objects of this type exist; instead, its methods are available on {{domxref("Window")}} for the standard browsing scope, or on {{domxref("WorkerGlobalScope")}} for workers.

- -

Properties

- -

This interface neither inherits nor provides any properties.

- -

Methods

- -

This interface does not inherit any methods. It offers the following methods.

- -
-
{{domxref("WindowTimers.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
-
{{domxref("WindowTimers.clearTimeout()")}}
-
Cancels the delayed execution set using {{domxref("WindowTimers.setTimeout()")}}.
-
{{domxref("WindowTimers.setInterval()")}}
-
Schedules a function to execute every time a given number of milliseconds elapses.
-
{{domxref("WindowTimers.setTimeout()")}}
-
Schedules a function to execute in a given amount of time.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

See also

- - diff --git a/files/uk/web/api/windowtimers/settimeout/index.html b/files/uk/web/api/windowtimers/settimeout/index.html deleted file mode 100644 index 19c90148ce..0000000000 --- a/files/uk/web/api/windowtimers/settimeout/index.html +++ /dev/null @@ -1,428 +0,0 @@ ---- -title: WindowTimers.setTimeout() -slug: Web/API/WindowTimers/setTimeout -translation_of: Web/API/WindowOrWorkerGlobalScope/setTimeout ---- -
{{APIRef("HTML DOM")}}
- -
 
- -
Метод setTimeout(), що належить об'єкту {{domxref("WindowOrWorkerGlobalScope")}}, та наслідується від window.setTimeout,  встановлює таймер, що виконує функцію або вказаний фрагмент коду один раз, щойно спливе заданий час.
- -
 
- -

Синтаксис

- -
var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
-var timeoutID = window.setTimeout(code[, delay]);
-
- -

Параметри

- -
-
func
-
{{jsxref("function")}} котру необхідно виконати після того, як вийде заданий час.
-
code
-
Опційний синтаксис, котрий дозволяє задавати рядок замість функції, котра компілюється і виконується при спрацюванні таймера. Використання цього синтаксису не рекомендовано з тих же ж причин, котрі роблять застосування {{jsxref("eval()")}} загрозою безпеці.
-
delay {{optional_inline}}
-
 
-
Час у мілісекундах (тисячних секунди), котрий таймер має зачекати перед тим, як виконати вказану функцію або код. Якщо цей параметр пропустити, буде використано значення 0. Варто зазначити, що справжній час затримки, може бути довшим. Дивіться розділ {{anch("Reasons for delays longer than specified","Причини, з яких затримка є фактично довшою ніж задано")}}
-
param1, ..., paramN {{optional_inline}}
-
Додаткові параметри, що передаються до func або code, щойно час таймера спливе.
-
- -
-

Зверніть увагу:  Internet Explorer 9 та більш ранні версії не підтримують додаткові параметри. Застосовуйте поліфіл, щобл уможливити цей функціонал (див. розділ Callback arguments).  

-
- -

Значення, що повертається

- -


- Після виклику setTimeout(), повертається timeoutID  - це не нульове цифрове значення, що використовується для ідентифікації створеного таймера. Цей ідентифікатор можна передати як параметр до {{domxref("Window.clearTimeout()")}} щоб відмінити таймер.

- -

Корисно знати, що setTimeout() та {{domxref("WindowTimers.setInterval", "setInterval()")}} використовують спільну колекцію ID ідентифікаторів, а також що  clearTimeout() та {{domxref("WindowTimers.clearInterval", "clearInterval()")}} технічно можуть бути взаємозамінними. Тим не менше, задля ясності, варто завжди зіставляти їх, аби не допускати помилок під час розробки коду. 

- -

Приклад

- -

У наступному прикладі створено дві кнопки на веб сторінці, що прив'язані до setTimeout() та clearTimeout() процесів. Після натискання на першу кнопку встановлюється таймер, що викликає діалогове вікно alert через дві секунди та зберігає ID таймера для подальшого використання у clearTimeout(). За бажанням ви можете відмінити цей таймер, якщо натисните другу кнопку.

- -

HTML код

- -
<p>Live Example</p>
-<button onclick="delayedAlert();">Відобразити діалогове вікно alert через дві секунди.</button>
-<p></p>
-<button onclick="clearAlert();">Відмінити відображення діалогового вікна.</button>
-
- -

JavaScript код

- -
var timeoutID;
-
-function delayedAlert() {
-  timeoutID = window.setTimeout(slowAlert, 2000);
-}
-
-function slowAlert() {
-  alert("Це було дійсно повільно!");
-}
-
-function clearAlert() {
-  window.clearTimeout(timeoutID);
-}
-
- -

Результат

- -

{{EmbedLiveSample('Example', 'Приклад')}}

- -

Дивіться також clearTimeout() example.

- -

Поліфіл

- -

Якщо вам необхідно передати один чи декілька аргументів до колбек функції, а також потрібно, щоб цей функціонал працював у браузерах, що не підтримують передачу додаткових аргументів для setTimeout() чи setInterval() (наприклад, версії Internet Explorer 9 чи нижче), ви можете застосувати цей поліфіл, який активує стандартну HTML5 функціональність. Просто додайте цей код на початку вашого скрипта: 

- -
/*\
-|*|
-|*|  Polyfill which enables the passage of arbitrary arguments to the
-|*|  callback functions of JavaScript timers (HTML5 standard syntax).
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/DOM/window.setInterval
-|*|
-|*|  Syntax:
-|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
-|*|  var timeoutID = window.setTimeout(code, delay);
-|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
-|*|  var intervalID = window.setInterval(code, delay);
-|*|
-\*/
-
-(function() {
-  setTimeout(function(arg1) {
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeST__ = window.setTimeout;
-    window.setTimeout = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeST__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-
-  var interval = setInterval(function(arg1) {
-    clearInterval(interval);
-    if (arg1 === 'test') {
-      // feature test is passed, no need for polyfill
-      return;
-    }
-    var __nativeSI__ = window.setInterval;
-    window.setInterval = function(vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */ ) {
-      var aArgs = Array.prototype.slice.call(arguments, 2);
-      return __nativeSI__(vCallback instanceof Function ? function() {
-        vCallback.apply(null, aArgs);
-      } : vCallback, nDelay);
-    };
-  }, 0, 'test');
-}())
-
- -

Фікс для IE

- -

Якщо вам потрібен фікс, який не впливатиме на роботу жодного іншого мобільного чи десктопного браузера, окрім IE9 та нижче, ви можете скористатись умовними коментарями JavaScript:

- -
/*@cc_on
-  // conditional IE < 9 only fix
-  @if (@_jscript_version <= 9)
-  (function(f){
-     window.setTimeout=f(window.setTimeout);
-     window.setInterval=f(window.setInterval);
-  })(function(f){return function(c,t){var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}});
-  @end
-@*/
-
- -

Або використати умовні коментарі HTML для IE9 та нижче:

- -
<!--[if lte IE 9]><script>
-(function(f){
-window.setTimeout=f(window.setTimeout);
-window.setInterval=f(window.setInterval);
-})(function(f){return function(c,t){
-var a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)}
-});
-</script><![endif]-->
-
- -

Тимчасові рішення

- -

Ще одне можливе рішення - використання анонімної функції для виклику колбека, але це вартісне рішення. Приклад:

- -
var intervalID = setTimeout(function() { myFunc("one", "two", "three"); }, 1000);
-
- -

Приклад, наведений вище, може бути також написаний за допомогою   arrow function:

- -
var intervalID = setTimeout(() => { myFunc("one", "two", "three"); }, 1000);
-
- -

Ще одне рішення - використання   function's bind. Приклад:

- -
setTimeout(function(arg1){}.bind(undefined, 10), 1000);
-
- -

Проблема "this"

- -

Коли ви передаєте до setTimeout() метод або будь-яку іншу функцію, ймовірно вона буде викликана не з тим значенням this, на яке ви очікуєте. Ця проблема детально описана у JavaScript reference.

- -

Пояснення

- -

Код, що виконується всередині setTimeout(), викликається із  іншого контекста виконання (execution context), ніж у функції, яка викликала setTimeout. До функції, яку викликають всередині setTimeout застосовуються звичайні правила призначення this. І, якщо ви не встановили this під час виклику або за допомогою bind, його значенням за замовчуванням буде об'єкт  global (або window) у нестрогому режимі, або undefined у строгому режимі. Значення this буде іншим, аніж у функції, яка викликала setTimeout. Розгляньте наступний приклад:

- -
myArray = ["zero", "one", "two"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-myArray.myMethod(); // prints "zero,one,two"
-myArray.myMethod(1); // prints "one"
- -

Приклад вище працює тому, що myMethod викликано, як метод масиву myArray. Тому його this дорівнює myArray, а значення this[sProperty] всередині метода дорівнює myArray[sProperty]. Тим не менше, у наступному прикладі:

- -
setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
-setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1.5 seconds
- -

Метод myArray.myMethod передано до setTimeout, як звичайну функцію, якій не задано значення this. І коли вона викликається, її this за замовчуванням дорівнює об'єкту window. У  setTimeout неможливо передати this аргументом, як, наприклад, у методи Array (forEach, reduce, тощо), або через використання  call, як показано у прикладі нижче:

- -
setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
-
- -

Можливі рішення

- -

Типовий спосіб вирішення цієї проблеми - використання функції обгортки, яка встановлює this із необхідним значенням: 

- -
setTimeout(function(){myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout(function(){myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
- -

Стрілочна функція також є прийнятною альтернативою:

- -
setTimeout(() => {myArray.myMethod()}, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout(() => {myArray.myMethod('1')}, 2500); // prints "one" after 2.5 seconds
- -

Ще одне можливе рішення проблеми this - замінити нативні глобальні функції setTimeout() та setInterval() кастомними функціями, які можуть приймати об'єкт this і застосовувати його у колбек функції, використовуючи  Function.prototype.call. Наприклад: 

- -
// Enable setting 'this' in JavaScript timers
-
-var __nativeST__ = window.setTimeout,
-    __nativeSI__ = window.setInterval;
-
-window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this,
-      aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeST__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
-
-window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
-  var oThis = this,
-      aArgs = Array.prototype.slice.call(arguments, 2);
-  return __nativeSI__(vCallback instanceof Function ? function () {
-    vCallback.apply(oThis, aArgs);
-  } : vCallback, nDelay);
-};
- -
Зверніть увагу:  Подібний підхід дозволяє передавати будь-яку кількість аргументів у колбек функцію таймерів навіть для IE. Таким чином, цей спосіб може також бути використаний як поліфіл. Перегляньте параграф Callback arguments .
- -

Випробування нового підхода:

- -
myArray = ["zero", "one", "two"];
-myArray.myMethod = function (sProperty) {
-    alert(arguments.length > 0 ? this[sProperty] : this);
-};
-
-setTimeout(alert, 1500, "Hello world!"); // the standard use of setTimeout and setInterval is preserved, but...
-setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
-setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2.5 seconds
-
- -
Зверніть увагу:  JavaScript 1.8.5 впровадив метод   Function.prototype.bind(), який встановлює значення this для кожного виклику вказаної функції. Це допомагає уникнути використання функції обгортки для призначення this колбека.
- -

Приклад використання bind():

- -
myArray = ["zero", "one", "two"];
-myBoundMethod = (function (sProperty) {
-    console.log(arguments.length > 0 ? this[sProperty] : this);
-}).bind(myArray);
-
-myBoundMethod(); // prints "zero,one,two" because 'this' is bound to myArray in the function
-myBoundMethod(1); // prints "one"
-setTimeout(myBoundMethod, 1000); // still prints "zero,one,two" after 1 second because of the binding
-setTimeout(myBoundMethod, 1500, "1"); // prints "one" after 1.5 seconds
-
- -

Примітки

- -

Таймер можна скасувати за допомогою {{domxref("Window.clearTimeout()")}}. Щоб викликати функцію повторно (наприклад, через кожні N мілісекунди), використовуйте  {{domxref("Window.setInterval()")}}.

- -

Важливо пам'ятати, що функція або фрагмент коду не можуть бути виконані, допоки не буде завершено поток функції, яка викликала setTimeout(). Наприклад. 

- -
function foo(){
-  console.log('foo has been called');
-}
-setTimeout(foo, 0);
-console.log('After setTimeout');
- -

Виведе в консоль:

- -
After setTimeout
-foo has been called
- -

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

- -

Passing string literals

- -

Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval.

- -
// Recommended
-window.setTimeout(function() {
-    alert("Hello World!");
-}, 500);
-
-// Not recommended
-window.setTimeout("alert('Hello World!');", 500);
-
- -

A string passed to setTimeout is evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

- -

Причини чому затримка є фактично довшою ніж вказано

- -

There are a number of reasons why a timeout may take longer to fire than anticipated. This section describes the most common reasons.

- -

Nested timeouts forced to >=4ms

- -

Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5.

- -

In fact, 4 ms is specified by the HTML5 spec and is consistent across browsers released in 2010 and onward. Prior to {{geckoRelease("5.0")}}, the minimum timeout value for nested timeouts was 10 ms.

- -

To implement a 0 ms timeout in a modern browser, you can use {{domxref("window.postMessage()")}} as described here.

- -

Timeouts in inactive tabs clamped to >=1000ms

- -

To reduce the load (and associated battery usage) from background tabs, timeouts are often clamped to firing no more often than once per second (1000 ms) in inactive tabs.

- -

Firefox implements this behavior since version 5 (see {{bug(633421)}}, the 1000ms constant can be tweaked through the dom.min_background_timeout_value preference). Chrome implements this behavior since version 11 (crbug.com/66078).

- -

Firefox for Android uses a timeout value of 15 minutes for background tabs since {{bug(736602)}} in Firefox 14, and background tabs can also be unloaded entirely.

- -
-

Firefox 50 no longer throttles background tabs if a Web Audio API {{domxref("AudioContext")}} is actively playing sound. Firefox 51 further amends this such that background tabs are no longer throttled if an {{domxref("AudioContext")}} is present in the tab at all, even if no sound is being played. These resolve a number of issues with apps which play note-based music not being able to time or synchronize the music properly when the tab is in the background.

-
- -

Late timeouts

- -

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks

- -

Maximum delay value

- -

Browsers including Internet Explorer, Chrome, Safari, and Firefox store the delay as a 32-bit signed integer internally. This causes an integer overflow when using delays larger than 2147483647, resulting in the timeout being executed immediately.

- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("HTML WHATWG", "webappapis.html#dom-settimeout", "WindowTimers.setTimeout()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1")}}4.04.01.0
Supports parameters for callback[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.01.0{{CompatGeckoMobile("1")}}6.06.01.0
Supports parameters for callback[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Whether it supports the optional parameters when in its first form or not.

- -

See also

- - diff --git "a/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/index.html" "b/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/index.html" deleted file mode 100644 index e1aab3dfde..0000000000 --- "a/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/index.html" +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Подія -slug: Web/API/Подія -translation_of: Web/API/Event ---- -

{{APIRef("DOM")}}

- -

Event інтерфейс представляє подію, що відбувається в DOM. Подія може бути ініційована дією користувача, наприклад, кліком мишки або натисканням клавіши на клавіатурі, або згенерована API, щоб показати прогрес асинхронного завдання, тощо. Це може бути також ініційовано програмно викликом HTMLElement.click() методу елемента, або створенням екземпляру події, потім відправленням його до вказаного цільового елементу, використовуючи EventTarget.dispatchEvent().

- -

Існує багато різновидів подій, деякі з котрих використовують інші інтерфейси, основані на головному інтерфейсі Event. Сам по собі Event вміщає можливості та методи, спільні для всіх подій.

- -

Багато елементів DOM можуть бути налаштовані прийняти (або "почути") ці події та виконати код у відповідь на процес їхньої обробки. Хендлери подій звичайно пов'язані або додаються до різноманітних HTML elements (таких як <button><div>, <span>, і т.п.) при використанні EventTarget.addEventListener(), а це, як правило, замінює використання атрибутів хендлера подій старого HTML. Надалі за необхідності додавання, такі хендлери також можна відключати, якщо потрібно, використовуючи removeEventListener().  

- -

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

- -

Коли є багато вкладених елементів, кожний зі своїм особистим хендлером (хендлерами), обробка подій може стати дуже складною - особливо там, де батьківський елемент отримує ту ж саму подію, що й її дочірній елемент, тому що "просторово" вони перетинаються і таким чином подія технічно з'являється в них обох, а порядок обробки таких подій залежить від параметрів вспливаючих подій та захоплення кожного обробника.

- -

Інтерфейси на основі Event

- -

Нижче надано список інтерфейсів, які існують на основі головного Event інтерфейсу, із ссилками на відповідну документацію в довіднику MDN API.

- -

Зверніть увагу, що всі інтерфейси подій мають назви із закінченням "Event".

- - - -
- -
- -

Конструктор

- -
-
{{domxref("Event.Event", "Event()")}}
-
Створює  Event об'єкт та повертає його абоненту.
-
- -

Властивості

- -
-
{{domxref("Event.bubbles")}} {{readonlyinline}}
-
Булевий вираз вказує на те, чи вспливає подія через DOM.
-
{{domxref("Event.cancelBubble")}}
-
Історичний псевдонім {{domxref("Event.stopPropagation()")}}. Встановлення його значення true  перед поверненням з обробника події запобігає поширенню події.
-
{{domxref("Event.cancelable")}} {{readonlyinline}}
-
Булевий вираз вказує на те, чи скасовується подія.
-
{{domxref("Event.composed")}} {{ReadOnlyInline}}
-
Булевий вираз вказує на те, чи може подія всплити через межу між  тінню DOM та черговим DOM.
-
{{domxref("Event.currentTarget")}} {{readonlyinline}}
-
Посилання на зареєстровану зараз ціль події. Це об'єкт, на котрий наразі планується відіслати подію. Можливо, це змінилося по дорозі через retargeting.
-
{{domxref("Event.deepPath")}} {{non-standard_inline}}
-
 {{jsxref("Array")}} of DOM {{domxref("Node")}}, через який всплила подія.
-
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
-
Вказує, чи виклик {{domxref("event.preventDefault()")}}  скасував подію.
-
{{domxref("Event.eventPhase")}} {{readonlyinline}}
-
Вказує, яка фаза потоку подій обробляється.
-
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
-
Явна оригінальна мета події (Mozilla-specific).
-
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
-
Початкова ціль події перед будь-якими ретаргетингами. (Mozilla-specific).
-
{{domxref("Event.returnValue")}}
-
Історична властивість, представлена Internet Explorer і згодом прийнята в специфікацію DOM для того, щоб забезпечити продовження  роботи існуючих сайтів. В ідеалі, вам слід спробувати використати {{domxref(''Event.preventDefault()")}} та {{domxref("Event.defaultPrevented")}} замість нього, але ви можете використовувати returnValue, якщо ви  вирішите це зробити.
-
{{domxref("Event.returnValue")}} {{non-standard_inline}}
-
Нестандартний псевдонім (зі старої версії Microsoft Internet Explorer) для {{domxref("Event.target")}}. Деякі інші браузери починають підтримувати його для веб-сумісності.
-
{{domxref("Event.target")}} {{readonlyinline}}
-
Посилання на ціль, до якої спочатку була відправлена подія.
-
{{domxref("Event.timeStamp")}} {{readonlyinline}}
-
Час, коли було створено подію (в мілісекундах).  За специфікацією, це значення - час з епохи - але насправді визначення браузерів різняться.Крім того, ведеться робота, щоб змінити його на {{domxref("DOMHighResTimeStamp")}} .
-
{{domxref("Event.isTrusted")}} {{readonlyinline}}
-
Вказує, чи  була подія ініційована браузером (наприклад, після натискання клавіши на клавіатурі користувачем) або за сценарієм (використовуючи метод створення подій, наприклад {{domxref("Event.initEvent")}}).
-
Застарілі властивості
-
- -

{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}

- -

Застарілі; використовуйте замість них {{domxref("Event.composed", "composed")}}. ({{jsxref("Boolean")}} вказує, чи вспливе дана подія через тіньовий корінь у стандарт DOM.)

- -

Методи

- -
-
{{domxref("Event.createEvent()")}} {{deprecated_inline}}
-
Створює нову подію, котра повинна бути ініційована викликом її  initEvent() методу.
-
{{domxref("Event.composedPath()")}}
-
Повертає шлях події (об'єкти, на які слухачі будуть викликані). Це не включає вузли через тіньові дерева, якщо тіньовий корінь було створено із закритим {{domxref("ShadowRootmode")}}.
-
{{domxref("Event.preventDefault()")}}
-
Скасовує подію, (якщо її можливо скасувати).
-
{{domxref("Event.stopImmediatePropagation()")}}
-
Для цієї конкретної події не дозволяйте викликати всіх інших слухачів. Сюди входять слухачі, приєднані до одного й того ж елемента, а також ті, що додаються до елементів, які буде прищеплено пізніше (наприклад, під час фази введення).
-
{{domxref("Event.stopPropagation()")}}
-
Зупиняє розповсюдження подій далі у DOM.
-
Застарілі методи
-
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
-
Нестандартний. Використовуйте замість нього {{domxref("Event.defaultPrevented")}}.  (Повертає значення {{domxref("Event.defaultPrevented")}}.)
-
{{domxref("Event.preventBubble()"}} {{non-standard_inline}} {{Obsolete_inline(24)}}
-
Застарілий; використовуйте замість нього {{domxref("event.stopPropagation")}}. (Захищає подію від вспливання).
-
{{domxref("Event.preventcapture()"}} {{non-standard_inline}} {{Obsolete_inline(24)}}
-
Застарілий; використовуйте замість нього {{domxref("event.stopPropagation"}}.
-
- -

Технічні характеристики

- - - - - - - - - - - - - - -
ХарактеристикаСтатусКоментар
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}}
- -

Сумісність з браузером

- -

приховано

- -

Таблиця сумісності на цій сторінці формується із структурованих даних. Якщо ви захочете побачити її, будь ласка, перевірте та відправте нам запит https://github/com/mdn/browser-compat-data

- - - -

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

- - diff --git "a/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/target/index.html" "b/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/target/index.html" deleted file mode 100644 index 20c17f2d31..0000000000 --- "a/files/uk/web/api/\320\277\320\276\320\264\321\226\321\217/target/index.html" +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Event.target -slug: Web/API/Подія/target -translation_of: Web/API/Event/target ---- -

{{ApiRef("DOM")}}

- -

Властивість target інтерфейсу {{domxref("Event")}} є посиланням на об'єкт який відправив подію. Він відрізняється від {{domxref("Event.currentTarget")}} коли обробник події викликається в фазі спливання або фіксації події.

- -

Синтаксис

- -
var theTarget = event.target;
- -

Приклад

- -

Властивість event.target може бути використана для реалізації делегування події.

- -
// Зробити список
-var ul = document.createElement('ul');
-document.body.appendChild(ul);
-
-var li1 = document.createElement('li');
-var li2 = document.createElement('li');
-ul.appendChild(li1);
-ul.appendChild(li2);
-
-function hide(e){
-  // e.target вказує на елемент <li> на якому було натиснуто
-  // Це відрізняється від e.currentTarget який буде посилатися на батьківський <ul> в даному контексті
-  e.target.style.visibility = 'hidden';
-}
-
-// Приєднання слухача подій до списка
-// Він запуститься при натисканні кожного <li>
-ul.addEventListener('click', hide, false);
-
- -

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

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
- -

Сумісність з браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Нотатки про сумісність

- -

В браузерах IE 6-8 використовується інша модель подій. Слухачі подій приєднуються з використанням нестандартного методу {{domxref('EventTarget.attachEvent')}}. В цій моделі, об'єкт події має {{domxref('Event.srcElement')}} властивість, замість властивості target, і воно має ту ж саму семантику як event.target.

- -
function hide(e) {
-  // Підтримка IE6-8
-  var target = e.target || e.srcElement;
-  target.style.visibility = 'hidden';
-}
-
- -

Читати також

- - 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 застосовні до всіх схем компонування. Більшість із них вживаються разом з однією-двома схемами і жодним чином не діють, якщо відповідний елемент компонується за іншою схемою.

-
- -

Див. також

- - diff --git a/files/uk/web/events/abort/index.html b/files/uk/web/events/abort/index.html deleted file mode 100644 index 40a9e144fc..0000000000 --- a/files/uk/web/events/abort/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: abort -slug: Web/Events/abort -translation_of: Web/API/HTMLMediaElement/abort_event -translation_of_original: Web/Events/abort ---- -

Подія abort спрацьовує коли завантаження ресурсу було перервано.

- -

Загальна інформація

- -
-
Специфікація
-
DOM L3
-
Interface
-
UIEvent if generated from a user interface, Event otherwise.
-
Bubbles
-
No
-
Cancelable
-
No
-
Target
-
Element
-
Default Action
-
None
-
- -

Властивості

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
diff --git a/files/uk/web/events/domcontentloaded/index.html b/files/uk/web/events/domcontentloaded/index.html deleted file mode 100644 index 96ca54cfb0..0000000000 --- a/files/uk/web/events/domcontentloaded/index.html +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: DOMContentLoaded -slug: Web/Events/DOMContentLoaded -translation_of: Web/API/Window/DOMContentLoaded_event ---- -

Подія DOMContentLoaded викликається, коли вихідний HTML документ повністю завантажився та був розібраний (parse), без очікування повного завантаження стилів, зображень, сабфреймів (subframes). Зовсім інша подія - load - має використовуватися лише для того, щоб визначити повне завантаження сторінки. Використання load там, де застосування DOMContentLoaded є більш доречним, є дуже поширеною помилкою, тому будьте уважними.

- -

{{Note("Синхронний Javascript затримує парсинг DOM.")}}

- -

{{Note("Існує безліч універсальних та автономних бібліотек, які  попонують кроссбраузерні методи для визначення готовності DOM.")}}

- -

Прискорення

- -

Якщо ви хочете, щоб DOM був розібраним (got parsed) якомога швидше після того, як користувач зробив запит сторінки, ви можете зробити ваш JavaScript асинхронним та оптимізувати завантаження стилів. Якщо цього не зробити, це сповільнить завантаження сторінки через те, що воно буде відбуватися паралельно і марнувати трафік у головного html документа.

- -

Основна інформація

- -
-
Специфікація
-
HTML5
-
Інтерфейс
-
Подія
-
Спливання
-
Так
-
Можливість скасування
-
Так (однак скасування як простої події скасувати не можна)
-
 
-
 
-
 
-
 
-
Ціль
-
Документ
-
Типова дія
-
Немає.
-
- -

Властивості

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ВластивістьТипОпис
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
- -

Приклад

- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-</script>
-
- -
<script>
-  document.addEventListener("DOMContentLoaded", function(event) {
-    console.log("DOM fully loaded and parsed");
-  });
-
-for(var i=0; i<1000000000; i++)
-{} // this synchronous script is going to delay parsing of the DOM. So the DOMContentLoaded event is going to launch later.
-</script>
-
- -

Сумісність з браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0[1]{{CompatGeckoDesktop("1")}}[1]9.0[2]9.03.1[1]
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile("1")}}[1]{{CompatUnknown}}[2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
-
- -

[1] Bubbling для цієї події підтримується принаймні Gecko 1.9.2, Chrome 6, and Safari 4.

- -

[2] Internet Explorer 8 підтримує подію readystatechange , яка може використовуватися для того, щоб визначити чи готовий DOM. У більш ранніх версіях Internet Explorer цей стан може бути визначений повторними спробами виконання document.documentElement.doScroll("left");,  так як цей фрагмент коду буде генерувати помилку, поки DOM не буде готовий.

- -

Подібні події

- - diff --git a/files/uk/web/guide/css/getting_started/index.html b/files/uk/web/guide/css/getting_started/index.html deleted file mode 100644 index cedd782ad2..0000000000 --- a/files/uk/web/guide/css/getting_started/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Getting started with CSS -slug: Web/Guide/CSS/Getting_started -translation_of: Learn/CSS/First_steps -translation_of_original: Web/Guide/CSS/Getting_started ---- -

Це керівництво ознайомить Вас з основними функціями та мовою (синтаксисом) каскадних таблиць стилів (Cascading Style Sheets - CSS). Ви використовуєте CSS, щоб змінити зовнішній вигляд структурованого документу, такого як веб-сторінка. Урок також включає приклади вправ, які ви можете спробувати виконати на власному комп’ютері, щоб побачити ефекти CSS і функції, що реалізуються в сучасних браузерах.

- -

Посібник призначений для початківців і будь-кого, хто б хотів повторити основи CSS. Якщо ви маєте більше досвіду з CSS, основна сторінка CSS містить списки більш просуненого рівня.

- - - -

Що потрібно для початку роботи

- - - -

Не зважаючи на те, що вправи можуть допомогти тобі в навчанні, ти не зобов’язаний хз виконувати. Ти можеш просто читати керівництво та розглядати зображення.

- -

На замітку: Керівництво розглядає тему як CSS працює з кольором. Буде простіше завершити ці секції з кольоровим дисплеєм та нормальним кольоровим зором.  

- -

Як використовувати це керівництво

- -

В опрацюванні цього керівництва читай сторінки уважно і в визначеній послідовності. Якщо ти пропустиш сторінку, надалі може бути важко зрозуміти наступні сторінки підручника. 

- -

Частина І: основи CSS

- -

На кожній сторінці переглянь відділ Інформація, щоб зрозуміти як працює CSS. Спробуй  секцію Дія, щоб випробувати CSS на власному комп’ютері.

- -

To test your understanding, take the challenge at the end of each page. Solutions to the challenges are linked under the challenges, so you don't need to look at them if you don't want to.

- -

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

- -

Частина II: Сфера CSS

- -

Друга частина підручника надає приклади, які показують сферу CSS з іншими веб- і Mozilla технологіями.

- -
    -
  1. JavaScript
  2. -
  3. SVG-графіка
  4. -
  5. XML дані
  6. -
  7. XBL сполучення
  8. -
  9. Користувацбкі інтерфейси ХUL
  10. -
diff --git a/files/uk/web/guide/css/getting_started/what_is_css/index.html b/files/uk/web/guide/css/getting_started/what_is_css/index.html deleted file mode 100644 index f1ee8b66b1..0000000000 --- a/files/uk/web/guide/css/getting_started/what_is_css/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: What is CSS? -slug: Web/Guide/CSS/Getting_started/What_is_CSS -translation_of: Learn/CSS/First_steps/How_CSS_works -translation_of_original: Web/Guide/CSS/Getting_started/What_is_CSS ---- -
{{CSSTutorialTOC}}
- -

{{previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started", "Getting started")}} This first section of the CSS Getting Started tutorial briefly explains Cascading Style Sheets (CSS). You'll also create a simple document to use for CSS exercises in subsequent sections.

- -

Інформація: Що таке CSS?

- -

Каскадні таблиці стилів (англ. - Cascading Style Sheets  CSS) - мова, що визначає як вміст сторінки буде візуально офрмлений та представлений користувачам. Складові документу ж описують мовою розмітки, на зразок HTML.

- -

Документ являє собою інформацію, структуровану для подання з використанням мови розмітки.

- -

Presenting a document to a user means converting it into a usable form for your audience. Browsers, like Firefox, Chrome or Internet Explorer, are designed to present documents visually, for example, on a computer screen, projector or printer.

- -
-

Приклади

- - -
- -

In this tutorial, boxes captioned Детальніше like the one below contain optional information and links to more resources on a concept or topic covered in a section. Read them as you see them, follow the links, or skip these boxes and return to read them later.

- -
-
Детальніше
- -

Документ- це не те ж саме, що і файл. Втім, ти можеш зберегти документ у файлі.

- -

Документ, який ти зараз читаєш не збережений окремим файлом. Коли твій веб-браузер переходить на цю сторінку, сервер робить запит до бази данних та генерує документ, зібравши частини документу з різних фалів. Однак, в цьому уроці ти будеш працювати також і з  документами, збереженими у файлах.

- -

Більше інформації про документи та мови розміток ти можеш знайти в фнших розділах цього веб-сайту:

- - - - - - - - - - - - - - - - - - - - -
HTMLдля веб-сторінок
XMLдля структурованих документів в загальному
SVGдля графіки
XULдля інтерфейсів користувачів у браузері Mozilla
- -

У другій частині ціього навчального посібника ти знайдеш приклади цих мов розміток.

-
- -
-
Детальніше
- -

In formal CSS terminology, the program that presents a document to a user is called a user agent (UA). A browser is just one kind of UA. CSS is not just for browsers or visual presentation, but for Part I of this tutorial, you'll only work with CSS in a browser.

- -

For formal definitions of terminology relating to CSS, see Definitions in the CSS Specification from the World Wide Web Consortium (W3C), an international community that sets open standards for the web.

-
- -

До роботи: Створення документу

- -
    -
  1. Створи нову паку на своєму комп'ютері для того, щоб зберігати та упорядковувати вправи з наших уроків.
  2. -
  3. Open your text editor and create a new text file. This file will contain the document for the next few tutorial exercises.
  4. -
  5. Copy and paste the HTML shown below. Save the file using the name doc1.html -
    <!DOCTYPE html>
    -<html>
    -  <head>
    -  <meta charset="UTF-8">
    -  <title>Sample document</title>
    -  </head>
    -
    -  <body>
    -    <p>
    -      <strong>C</strong>ascading
    -      <strong>S</strong>tyle
    -      <strong>S</strong>heets
    -    </p>
    -  </body>
    -</html>
    - -

    {{ LiveSampleLink('Action_Creating_a_document', 'View above Demo') }}

    -
  6. -
  7. Open a new tab or a new window in your browser, then open the file you just created. -

    You should see the text with the initial letters bold, like this:

    - - - - - - - -
    Cascading Style Sheets
    - -

    What you see in your browser might not look exactly the same because of settings in your browser and in this wiki. Some differences in the font, spacing and colors are not important.

    -
  8. -
- -

Що далі?

- -

{{nextPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Why_use_CSS", "Why use CSS?")}}Your document does not yet use CSS. In the next section you'll use CSS to style your document.

diff --git a/files/uk/web/guide/graphics/index.html b/files/uk/web/guide/graphics/index.html new file mode 100644 index 0000000000..57af0fdbc3 --- /dev/null +++ b/files/uk/web/guide/graphics/index.html @@ -0,0 +1,49 @@ +--- +title: Графіка для Web +slug: Web/Guide/Графіка +tags: + - 2D + - 3D + - Canvas + - HTML5 + - SVG + - WebGL + - WebRTC + - Веб + - Графіка +translation_of: Web/Guide/Graphics +--- +

Сучасним сайтам і веб-додаткам потрібне відображення графіки. Статичні зображення легко зобразити використовуючи елемент {{HTMLElement("img")}}, чи налаштувати фон HTML елементів використовуючи властивість {{cssxref("background-image")}}. Ви також можете конструювати графіку на льоту, або модифікувати її після. В статтях далі сказано як це можна зробити.

+ +
+
+

2D Графіка

+ +
+
Canvas
+
Елемент {{HTMLElement("canvas")}} надає зручні API для малювання 2D графіки використовуючи JavaScript.
+
SVG
+
Scalable Vector Graphics (SVG) дозволяє використовувати лінії, криві, та інші геометричні фігури для рендерингу графіки. З векторів, ви можете створювати зображення які не втрачають якості при маштабуванні.
+
+ +

Переглянути все...

+
+ +
+

3D Графіка

+ +
+
WebGL
+
Посібник для початку роботи з WebGL, API для роботи з 3D графікою в веб. Ця технологія дає вам можливість використовувати стандартний OpenGL ES в Web контенті.
+
+ +

Відео

+ +
+
Використання HTML5 аудіо і відео
+
Вбудовування відео і/або аудіо в веб-сторінки і керування відтворенням.
+
WebRTC
+
RTC в WebRTC означає Real-Time Communications (комунікація в реальному часі), технологія яка дозволяє передавати потокове аудіо/відео і дані між кліентами браузера (пірами).
+
+
+
diff --git a/files/uk/web/guide/html/using_html_sections_and_outlines/index.html b/files/uk/web/guide/html/using_html_sections_and_outlines/index.html new file mode 100644 index 0000000000..84db2e6a76 --- /dev/null +++ b/files/uk/web/guide/html/using_html_sections_and_outlines/index.html @@ -0,0 +1,337 @@ +--- +title: Використання HTML-секцій та структура документу +slug: Web/Guide/HTML/Використання_HTML-секцій_та_структура_документу +translation_of: Web/Guide/HTML/Using_HTML_sections_and_outlines +--- +
+

 В перекладі наводяться терміни схема документу та алгоритм схематизації у відповідності до англійських outline та outline algorithm, оскільки на думку перекладача найбільш точно відповідають змісту, вкладеному в поняття на мові оригінлу.

+ +

Також у відповідності до section та subsection використано розділ та підрозділ, так як в змісті даного документу йдеться більше про великі веб-сторінки, порівнювані із книжками.

+
+ +
+

Зверніть увагу: На даний момент немає відомих реалізацій алгоритму побудови схеми документа в браузерах чи інших агентах користувачів (assistive technology user agents), проте алгоритм реалізований в  ішому програмному забезпеченні, наприклад, в засобах перевірки стандартів (conformance checkers). Therefore the outline algorithm cannot be relied upon to convey document structure to users. Автори рекомендують використовувати ранг заголовку (h1-h6) для опису структури документу.

+
+ +

Специфікація HTML 5 вводить ряд нових елементів, що дозволяють веб-розробникам краще описувати структуру веб-документу використовуючи стандартну семантику. Даний документ описує ці елементи та способи їх використання для створення бажаної схеми документу.

+ +

Структура документу в HTML 4

+ +

Структура документу, тобто семантична структура, що знаходиться між <body> і </body>, — основа представлення сторінки. В HTML4 для опису структури документу використовується форма запису із розділів та підрозділів. Розділ визначається за допомогою елемента ({{HTMLElement("div")}}), в який включаються елементи заголовків ({{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, або {{HTMLElement("h6")}}), які, власне, і слугують заголовками секцій чи підсекцій. Взаєморозміщення даних елементів утворює структуру документу та будує його схему.

+ +

Таким чином наступна розмітка:

+ +
+
<div class="section" id="forest-elephants" >
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <div class="subsection" id="forest-habitat" >
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them.
+     ...this subsection continues...
+  </div>
+</div>
+
+
+ +

зводиться до наступної схеми:

+ +
1. Forest elephants
+   1.1 Habitat
+
+ +

Елемент {{HTMLElement("div")}} не оголошує нову секцію. Для цього достатньо наявності тегу заголовка. Таким чином фрамент:

+ +
<h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h2>Habitat</h2>
+  <p>Forest elephants do not live in trees but among them.
+    ...this subsection continues...
+  <h2>Diet</h2>
+<h1>Mongolian gerbils</h1>
+
+ +

зумовлює наступну схему:

+ +
1. Forest elephants
+   1.1 Habitat
+   1.2 Diet
+2. Mongolian gerbils
+
+ +

Проблеми, розв'зані за допомогою HTML5

+ +

Спосіб визначення структури документу в HTML 4 та обробка її алгоритмом схематизації є досить складнм та зумовлює наступні проблеми:

+ +
    +
  1. Використання елементу {{HTMLElement("div")}}  для оголошення секцій (розділів) без використання спеціальних класів (значень атрибуту class) робить неможливим застосування алгоритму схематизації ("Цей {{HTMLElement("div")}} — частина схеми сторінки, що визначає секцію чи підсекцію?" Чи "це звичайний {{HTMLElement("div")}}-елемент, використаний для стилізації?"). Іншими словами, специфікація HTML 4 дуже неточно визначає межі початку та закінчення розділів. Автоматична генерація схеми документу досить важлива, зокрема для реабілітаційних технологій, які адаптують та доносять інформацію до людей (від перекл.: як правило, з обмеженими можливостями) базуючись на структурі документу. HTML 5 усуває труднощі обробки елементу {{HTMLElement("div")}} алгоритмом схематизації, оскільки вводить новий елемент для розділів, {{HTMLElement("section")}}, HTML Section Element.
  2. +
  3. Merging several documents is hard: inclusion of a sub-document in a main document means changing the level of the HTML Headings Element so that the outline is kept. This is solved in HTML5 as the newly introduced sectioning elements ({{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}} and {{HTMLElement("aside")}}) are always subsections of their nearest ancestor section, regardless of what sections are created by internal headings.
  4. +
  5. In HTML4, every section is part of the document outline. But documents are often not that linear. A document can have special sections containing information that is not part of, though it is related to, the main flow, like an advertisement block or an explanation box. HTML5 introduces the {{HTMLElement("aside")}} element allowing such sections to not be part of the main outline.
  6. +
  7. Again, in HTML4, because every section is part of the document outline, there is no way to have sections containing information related not to the document but to the whole site, like logos, menus, table of contents, or copyright information and legal notices. For that purpose, HTML5 introduces three new elements: {{HTMLElement("nav")}} for collections of links, such as a table of contents, {{HTMLElement("footer")}} and {{HTMLElement("header")}} for site-related information. Note that {{HTMLElement("header")}} and {{HTMLElement("footer")}} are not sectioning content like {{HTMLElement("section")}}, rather, they exist to semantically mark up parts of a section.
  8. +
+ +

More generally, HTML5 brings precision to the sectioning and heading features, allowing document outlines to be predictable and used by the browser to improve the user experience.

+ +

Алгоритм схематизації HTML 5

+ +

Let's consider the algorithms  underlying the way HTML handles sections and outlines.

+ +

Defining sections

+ +

All content lying inside the {{HTMLElement("body")}} element is part of a section. Sections in HTML5 can be nested. Beside the main section, defined by the {{HTMLElement("body")}} element, section limits are defined either explicitly or implicitly. Explicitly-defined sections are the content within {{HTMLElement("body")}},  {{HTMLElement("section")}},  {{HTMLElement("article")}},  {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} tags. 

+ +
Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}
+ +

Let's look at an example — here we have a document with a top level section and a footer defined. Inside the top level section we have three subsections, defined by two {{htmlelement("section")}} elements and an {{htmlelement("aside")}} element:

+ +
<section>
+
+  <h1>Forest elephants</h1>
+
+  <section>
+    <h1>Introduction</h1>
+    <p>In this section, we discuss the lesser known forest elephants.</p>
+  </section>
+
+  <section>
+    <h1>Habitat</h1>
+    <p>Forest elephants do not live in trees but among them.</p>
+  </section>
+
+  <aside>
+    <p>advertising block</p>
+  </aside>
+
+</section>
+
+<footer>
+  <p>(c) 2010 The Example company</p>
+</footer>
+ +

This leads to the following outline:

+ +
1. Forest elephants
+   1.1 Introduction
+   1.2 Habitat
+
+ +

Defining headings

+ +

While the HTML Sectioning elements define the structure of the document, an outline also needs headings to be useful. The basic rule is simple: the first HTML heading element (one of {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}) defines the heading of the current section.

+ +

The heading elements have a rank given by the number in the element name, where {{HTMLElement("h1")}} has the highest rank, and {{HTMLElement("h6")}} has the lowest rank. Relative ranking matters only within a section; the structure of the sections determines the outline, not the heading rank of the sections. For example, consider this code:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <section>
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them.
+        ...this subsection continues...
+  </section>
+</section>
+<section>
+  <h3>Mongolian gerbils</h3>
+  <p>In this section, we discuss the famous mongolian gerbils.
+     ...this section continues...
+</section>
+ +

This creates the following outline:

+ +
1. Forest elephants
+   1.1 Habitat
+2. Mongolian gerbils
+ +

Note that the rank of the heading element (in the example {{HTMLElement("h1")}} for the first top-level section, {{HTMLElement("h2")}} for the subsection and {{HTMLElement("h3")}} for the second top-level section) is not important. (Any rank can be used as the heading of an explicitly-defined section, although this practice is not recommended.)

+ +

Implicit sectioning

+ +

Because the HTML5 Sectioning Elements aren't mandatory to define an outline, to keep compatibility with the existing web dominated by HTML4, there is a way to define sections without them. This is called implicit sectioning.

+ +

The heading elements ({{HTMLElement("h1")}} to {{HTMLElement("h6")}}) define a new, implicit, section when they aren't the first heading of their parent, explicit, sections. The way this implicit section is positioned in the outline is defined by its relative rank with the previous heading in their parent section. If it is of a lower rank than the previous heading, it opens an implicit sub-section of the section. This code:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h3 class="implicit subsection">Habitat</h3>
+  <p>Forest elephants do not live in trees but among them.
+    ...this subsection continues...
+</section>
+ +

leading to the following outline:

+ +
1. Forest elephants
+   1.1 Habitat (implicitly defined by the h3 element)
+
+ +

If it is of the same rank as the previous heading, it closes the previous section (which may have been explicit!) and opens a new implicit one at the same level: 

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h1 class="implicit section">Mongolian gerbils</h1>
+  <p>Mongolian gerbils are cute little mammals.
+    ...this section continues...
+</section>
+ +

leading to the following outline: 

+ +
1. Forest elephants
+2. Mongolian gerbils (implicitly defined by the h1 element, which closed the previous section at the same time)
+
+ +

If it is of a higher rank than the previous heading, it closes the previous section and opens a new implicit one at the higher level:

+ +
<body>
+  <h1>Mammals</h1>
+  <h2>Whales</h2>
+  <p>In this section, we discuss the swimming whales.
+    ...this section continues...
+  <section>
+    <h3>Forest elephants</h3>
+    <p>In this section, we discuss the lesser known forest elephants.
+      ...this section continues...
+    <h3>Mongolian gerbils</h3>
+      <p>Hordes of gerbils have spread their range far beyond Mongolia.
+         ...this subsection continues...
+    <h2>Reptiles</h2>
+      <p>Reptiles are animals with cold blood.
+          ...this section continues...
+  </section>
+</body>
+ +

leading to the following outline:

+ +
1. Mammals
+   1.1 Whales (implicitly defined by the h2 element)
+   1.2 Forest elephants (explicitly defined by the section element)
+   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
+2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)
+
+ +

This is not the outline that one might expect by quickly glancing at the heading tags. To make your markup human-understandable, it is a good practice to use explicit tags for opening and closing sections, and to match the heading rank to the intended section nesting level. However, this is not required by the HTML5 specification. If you find that browsers are rendering your document outline in unexpected ways, check whether you have sections that are implicitly closed by heading elements.

+ +

An exception to the rule of thumb that heading rank should match the section nesting level is for sections that may be reused in multiple documents. For example, a section might be stored in a content-management system and assembled into documents at run time. In this case, a good practice is to start at {{HTMLElement("h1")}} for the top heading level of the reusable section. The nesting level of the reusable section will be determined by the section hierarchy of the document in which it appears. Explicit section tags are still helpful in this case.

+ +

Sectioning roots

+ +

 A sectioning root is an HTML element that can have its own outline, but the sections and headings inside it does not contribute to the outline of its ancestor. Beside {{HTMLElement("body")}} which is the logical sectioning root of a document, these are often elements that introduce external content to the page: {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}} and {{HTMLElement("td")}}.

+ +

Example:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <section>
+    <h2>Introduction</h2>
+    <p>In this section, we discuss the lesser known forest elephants</p>
+  </section>
+  <section>
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them. Let's
+       look what scientists are saying in "<cite>The Forest Elephant in Borneo</cite>":</p>
+    <blockquote>
+       <h1>Borneo</h1>
+       <p>The forest element lives in Borneo...</p>
+    </blockquote>
+  </section>
+</section>
+
+ +

This example results in the following outline:

+ +
1. Forest elephants
+   1.1 Introduction
+   1.2 Habitat
+ +

This outline doesn't contain the internal outline of the {{HTMLElement("blockquote")}} element, which, being an external citation, is a sectioning root and isolates its internal outline.

+ +

Sections outside the outline

+ +

 HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:

+ +
    +
  1. The HTML Aside Section Element ({{HTMLElement("aside")}}) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. It has its own outline, but doesn't belong to the main one.
  2. +
  3. The HTML Navigational Section Element ({{HTMLElement("nav")}}) defines a section that contains navigation links. There can be several of them in a document, for example one with page internal links like a table of contents, and another with site navigational links. These links are not part of the main document flow and outline, and are generally not initially rendered by screen readers and similar assistive technologies.
  4. +
+ +

Headers and Footers

+ +

HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:

+ +
    +
  1. The HTML Header Element ({{HTMLElement("header")}}) defines a page header — typically containing the logo and name of the site and possibly a horizontal menu — or section header, containing perhaps the section's heading, author name, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("header")}}. Despite its name, it is not necessarily positioned at the beginning of the page or section.
  2. +
  3. The HTML Footer Element ({{HTMLElement("footer")}}) defines a page footer — typically containing the copyright and legal notices and sometimes some links — or section footer, containing perhaps the section's publication date, license information, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("footer")}}. Despite its name, it is not necessarily positioned at the end of the page or section.
  4. +
+ +

These do not create new sections in the outline, rather, they mark up content inside sections of the page.

+ +

Addresses in sectioning elements

+ +

The author of a document often wants to publish some contact information, such as the author's name and address. HTML4 allowed this via the {{HTMLElement("address")}} element, which has been extended in HTML5.

+ +

A document can be made of different sections from different authors. A section from another author than the one of the main page is defined using the {{HTMLElement("article")}} element. Consequently, the {{HTMLElement("address")}} element is now linked to its nearest {{HTMLElement("body")}} or {{HTMLElement("article")}} ancestor.

+ +

Using HTML5 elements in non-HTML5 browsers

+ +

Sections and headings elements should work in most non-HTML5 browsers. Though unsupported, they don't need a special DOM interface and they only need a specific CSS styling as unknown elements are styled as display:inline by default:

+ +
section, article, aside, footer, header, nav, hgroup {
+  display:block;
+}
+
+ +

Of course the web developer can style them differently, but keep in mind that in a non-HTML5 browser, the default styling is different from what is expected for such elements. Also note that the {{HTMLElement("time")}} element has not been included, because the default styling for it in a non-HTML5 browser is the same as the one in an HTML5-compatible one.

+ +

This method has its limitation though, as some browsers do not allow styling of unsupported elements. That is the case of the Internet Explorer (version 8 and earlier), which need a specific script to allow this:

+ +
<!--[if lt IE 9]>
+  <script>
+    document.createElement("header" );
+    document.createElement("footer" );
+    document.createElement("section");
+    document.createElement("aside"  );
+    document.createElement("nav"    );
+    document.createElement("article");
+    document.createElement("hgroup" );
+    document.createElement("time"   );
+  </script>
+<![endif]-->
+ +

This script means that, in the case of Internet Explorer (8 and earlier), scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they won't be displayed, which may be problematic as these elements are likely defining the structure of the whole page. That's why an explicit {{HTMLElement("noscript")}} element should be added for this case:

+ +
<noscript>
+   <strong>Warning !</strong>
+   Because your browser does not support HTML5, some elements are simulated using JScript.
+   Unfortunately your browser has disabled scripting. Please enable it in order to display this page.
+</noscript>
+ +

This leads to the following code to allow the support of the HTML5 sections and headings elements in non-HTML5 browsers, even for Internet Explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting:

+ +
<!--[if lt IE 9]>
+  <script>
+    document.createElement("header" );
+    document.createElement("footer" );
+    document.createElement("section");
+    document.createElement("aside"  );
+    document.createElement("nav"    );
+    document.createElement("article");
+    document.createElement("hgroup" );
+    document.createElement("time"   );
+  </script>
+  <noscript>
+     <strong>Warning !</strong>
+     Because your browser does not support HTML5, some elements are created using JavaScript.
+     Unfortunately your browser has disabled scripting. Please enable it in order to display this page.
+  </noscript>
+<![endif]-->
+ +

Підсумок

+ +

Нові семантичні елементи, що були введені стандартом HTML5 забезпечили можливість описувати структуру документу єдиним стандартеризованим способом. They bring a big advantage for people having HTML5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. These new semantic elements are simple to use and, with very few burdens, can be made to work also in non-HTML5 browsers. Therefore they should be used without restrictions.

+ +
{{HTML5ArticleTOC()}}
diff --git "a/files/uk/web/guide/html/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_html-\321\201\320\265\320\272\321\206\321\226\320\271_\321\202\320\260_\321\201\321\202\321\200\321\203\320\272\321\202\321\203\321\200\320\260_\320\264\320\276\320\272\321\203\320\274\320\265\320\275\321\202\321\203/index.html" "b/files/uk/web/guide/html/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_html-\321\201\320\265\320\272\321\206\321\226\320\271_\321\202\320\260_\321\201\321\202\321\200\321\203\320\272\321\202\321\203\321\200\320\260_\320\264\320\276\320\272\321\203\320\274\320\265\320\275\321\202\321\203/index.html" deleted file mode 100644 index 84db2e6a76..0000000000 --- "a/files/uk/web/guide/html/\320\262\320\270\320\272\320\276\321\200\320\270\321\201\321\202\320\260\320\275\320\275\321\217_html-\321\201\320\265\320\272\321\206\321\226\320\271_\321\202\320\260_\321\201\321\202\321\200\321\203\320\272\321\202\321\203\321\200\320\260_\320\264\320\276\320\272\321\203\320\274\320\265\320\275\321\202\321\203/index.html" +++ /dev/null @@ -1,337 +0,0 @@ ---- -title: Використання HTML-секцій та структура документу -slug: Web/Guide/HTML/Використання_HTML-секцій_та_структура_документу -translation_of: Web/Guide/HTML/Using_HTML_sections_and_outlines ---- -
-

 В перекладі наводяться терміни схема документу та алгоритм схематизації у відповідності до англійських outline та outline algorithm, оскільки на думку перекладача найбільш точно відповідають змісту, вкладеному в поняття на мові оригінлу.

- -

Також у відповідності до section та subsection використано розділ та підрозділ, так як в змісті даного документу йдеться більше про великі веб-сторінки, порівнювані із книжками.

-
- -
-

Зверніть увагу: На даний момент немає відомих реалізацій алгоритму побудови схеми документа в браузерах чи інших агентах користувачів (assistive technology user agents), проте алгоритм реалізований в  ішому програмному забезпеченні, наприклад, в засобах перевірки стандартів (conformance checkers). Therefore the outline algorithm cannot be relied upon to convey document structure to users. Автори рекомендують використовувати ранг заголовку (h1-h6) для опису структури документу.

-
- -

Специфікація HTML 5 вводить ряд нових елементів, що дозволяють веб-розробникам краще описувати структуру веб-документу використовуючи стандартну семантику. Даний документ описує ці елементи та способи їх використання для створення бажаної схеми документу.

- -

Структура документу в HTML 4

- -

Структура документу, тобто семантична структура, що знаходиться між <body> і </body>, — основа представлення сторінки. В HTML4 для опису структури документу використовується форма запису із розділів та підрозділів. Розділ визначається за допомогою елемента ({{HTMLElement("div")}}), в який включаються елементи заголовків ({{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, або {{HTMLElement("h6")}}), які, власне, і слугують заголовками секцій чи підсекцій. Взаєморозміщення даних елементів утворює структуру документу та будує його схему.

- -

Таким чином наступна розмітка:

- -
-
<div class="section" id="forest-elephants" >
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <div class="subsection" id="forest-habitat" >
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-     ...this subsection continues...
-  </div>
-</div>
-
-
- -

зводиться до наступної схеми:

- -
1. Forest elephants
-   1.1 Habitat
-
- -

Елемент {{HTMLElement("div")}} не оголошує нову секцію. Для цього достатньо наявності тегу заголовка. Таким чином фрамент:

- -
<h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h2>Habitat</h2>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-  <h2>Diet</h2>
-<h1>Mongolian gerbils</h1>
-
- -

зумовлює наступну схему:

- -
1. Forest elephants
-   1.1 Habitat
-   1.2 Diet
-2. Mongolian gerbils
-
- -

Проблеми, розв'зані за допомогою HTML5

- -

Спосіб визначення структури документу в HTML 4 та обробка її алгоритмом схематизації є досить складнм та зумовлює наступні проблеми:

- -
    -
  1. Використання елементу {{HTMLElement("div")}}  для оголошення секцій (розділів) без використання спеціальних класів (значень атрибуту class) робить неможливим застосування алгоритму схематизації ("Цей {{HTMLElement("div")}} — частина схеми сторінки, що визначає секцію чи підсекцію?" Чи "це звичайний {{HTMLElement("div")}}-елемент, використаний для стилізації?"). Іншими словами, специфікація HTML 4 дуже неточно визначає межі початку та закінчення розділів. Автоматична генерація схеми документу досить важлива, зокрема для реабілітаційних технологій, які адаптують та доносять інформацію до людей (від перекл.: як правило, з обмеженими можливостями) базуючись на структурі документу. HTML 5 усуває труднощі обробки елементу {{HTMLElement("div")}} алгоритмом схематизації, оскільки вводить новий елемент для розділів, {{HTMLElement("section")}}, HTML Section Element.
  2. -
  3. Merging several documents is hard: inclusion of a sub-document in a main document means changing the level of the HTML Headings Element so that the outline is kept. This is solved in HTML5 as the newly introduced sectioning elements ({{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}} and {{HTMLElement("aside")}}) are always subsections of their nearest ancestor section, regardless of what sections are created by internal headings.
  4. -
  5. In HTML4, every section is part of the document outline. But documents are often not that linear. A document can have special sections containing information that is not part of, though it is related to, the main flow, like an advertisement block or an explanation box. HTML5 introduces the {{HTMLElement("aside")}} element allowing such sections to not be part of the main outline.
  6. -
  7. Again, in HTML4, because every section is part of the document outline, there is no way to have sections containing information related not to the document but to the whole site, like logos, menus, table of contents, or copyright information and legal notices. For that purpose, HTML5 introduces three new elements: {{HTMLElement("nav")}} for collections of links, such as a table of contents, {{HTMLElement("footer")}} and {{HTMLElement("header")}} for site-related information. Note that {{HTMLElement("header")}} and {{HTMLElement("footer")}} are not sectioning content like {{HTMLElement("section")}}, rather, they exist to semantically mark up parts of a section.
  8. -
- -

More generally, HTML5 brings precision to the sectioning and heading features, allowing document outlines to be predictable and used by the browser to improve the user experience.

- -

Алгоритм схематизації HTML 5

- -

Let's consider the algorithms  underlying the way HTML handles sections and outlines.

- -

Defining sections

- -

All content lying inside the {{HTMLElement("body")}} element is part of a section. Sections in HTML5 can be nested. Beside the main section, defined by the {{HTMLElement("body")}} element, section limits are defined either explicitly or implicitly. Explicitly-defined sections are the content within {{HTMLElement("body")}},  {{HTMLElement("section")}},  {{HTMLElement("article")}},  {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} tags. 

- -
Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}
- -

Let's look at an example — here we have a document with a top level section and a footer defined. Inside the top level section we have three subsections, defined by two {{htmlelement("section")}} elements and an {{htmlelement("aside")}} element:

- -
<section>
-
-  <h1>Forest elephants</h1>
-
-  <section>
-    <h1>Introduction</h1>
-    <p>In this section, we discuss the lesser known forest elephants.</p>
-  </section>
-
-  <section>
-    <h1>Habitat</h1>
-    <p>Forest elephants do not live in trees but among them.</p>
-  </section>
-
-  <aside>
-    <p>advertising block</p>
-  </aside>
-
-</section>
-
-<footer>
-  <p>(c) 2010 The Example company</p>
-</footer>
- -

This leads to the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
-
- -

Defining headings

- -

While the HTML Sectioning elements define the structure of the document, an outline also needs headings to be useful. The basic rule is simple: the first HTML heading element (one of {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}) defines the heading of the current section.

- -

The heading elements have a rank given by the number in the element name, where {{HTMLElement("h1")}} has the highest rank, and {{HTMLElement("h6")}} has the lowest rank. Relative ranking matters only within a section; the structure of the sections determines the outline, not the heading rank of the sections. For example, consider this code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-        ...this subsection continues...
-  </section>
-</section>
-<section>
-  <h3>Mongolian gerbils</h3>
-  <p>In this section, we discuss the famous mongolian gerbils.
-     ...this section continues...
-</section>
- -

This creates the following outline:

- -
1. Forest elephants
-   1.1 Habitat
-2. Mongolian gerbils
- -

Note that the rank of the heading element (in the example {{HTMLElement("h1")}} for the first top-level section, {{HTMLElement("h2")}} for the subsection and {{HTMLElement("h3")}} for the second top-level section) is not important. (Any rank can be used as the heading of an explicitly-defined section, although this practice is not recommended.)

- -

Implicit sectioning

- -

Because the HTML5 Sectioning Elements aren't mandatory to define an outline, to keep compatibility with the existing web dominated by HTML4, there is a way to define sections without them. This is called implicit sectioning.

- -

The heading elements ({{HTMLElement("h1")}} to {{HTMLElement("h6")}}) define a new, implicit, section when they aren't the first heading of their parent, explicit, sections. The way this implicit section is positioned in the outline is defined by its relative rank with the previous heading in their parent section. If it is of a lower rank than the previous heading, it opens an implicit sub-section of the section. This code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h3 class="implicit subsection">Habitat</h3>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-</section>
- -

leading to the following outline:

- -
1. Forest elephants
-   1.1 Habitat (implicitly defined by the h3 element)
-
- -

If it is of the same rank as the previous heading, it closes the previous section (which may have been explicit!) and opens a new implicit one at the same level: 

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h1 class="implicit section">Mongolian gerbils</h1>
-  <p>Mongolian gerbils are cute little mammals.
-    ...this section continues...
-</section>
- -

leading to the following outline: 

- -
1. Forest elephants
-2. Mongolian gerbils (implicitly defined by the h1 element, which closed the previous section at the same time)
-
- -

If it is of a higher rank than the previous heading, it closes the previous section and opens a new implicit one at the higher level:

- -
<body>
-  <h1>Mammals</h1>
-  <h2>Whales</h2>
-  <p>In this section, we discuss the swimming whales.
-    ...this section continues...
-  <section>
-    <h3>Forest elephants</h3>
-    <p>In this section, we discuss the lesser known forest elephants.
-      ...this section continues...
-    <h3>Mongolian gerbils</h3>
-      <p>Hordes of gerbils have spread their range far beyond Mongolia.
-         ...this subsection continues...
-    <h2>Reptiles</h2>
-      <p>Reptiles are animals with cold blood.
-          ...this section continues...
-  </section>
-</body>
- -

leading to the following outline:

- -
1. Mammals
-   1.1 Whales (implicitly defined by the h2 element)
-   1.2 Forest elephants (explicitly defined by the section element)
-   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
-2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)
-
- -

This is not the outline that one might expect by quickly glancing at the heading tags. To make your markup human-understandable, it is a good practice to use explicit tags for opening and closing sections, and to match the heading rank to the intended section nesting level. However, this is not required by the HTML5 specification. If you find that browsers are rendering your document outline in unexpected ways, check whether you have sections that are implicitly closed by heading elements.

- -

An exception to the rule of thumb that heading rank should match the section nesting level is for sections that may be reused in multiple documents. For example, a section might be stored in a content-management system and assembled into documents at run time. In this case, a good practice is to start at {{HTMLElement("h1")}} for the top heading level of the reusable section. The nesting level of the reusable section will be determined by the section hierarchy of the document in which it appears. Explicit section tags are still helpful in this case.

- -

Sectioning roots

- -

 A sectioning root is an HTML element that can have its own outline, but the sections and headings inside it does not contribute to the outline of its ancestor. Beside {{HTMLElement("body")}} which is the logical sectioning root of a document, these are often elements that introduce external content to the page: {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}} and {{HTMLElement("td")}}.

- -

Example:

- -
<section>
-  <h1>Forest elephants</h1>
-  <section>
-    <h2>Introduction</h2>
-    <p>In this section, we discuss the lesser known forest elephants</p>
-  </section>
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them. Let's
-       look what scientists are saying in "<cite>The Forest Elephant in Borneo</cite>":</p>
-    <blockquote>
-       <h1>Borneo</h1>
-       <p>The forest element lives in Borneo...</p>
-    </blockquote>
-  </section>
-</section>
-
- -

This example results in the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
- -

This outline doesn't contain the internal outline of the {{HTMLElement("blockquote")}} element, which, being an external citation, is a sectioning root and isolates its internal outline.

- -

Sections outside the outline

- -

 HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:

- -
    -
  1. The HTML Aside Section Element ({{HTMLElement("aside")}}) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. It has its own outline, but doesn't belong to the main one.
  2. -
  3. The HTML Navigational Section Element ({{HTMLElement("nav")}}) defines a section that contains navigation links. There can be several of them in a document, for example one with page internal links like a table of contents, and another with site navigational links. These links are not part of the main document flow and outline, and are generally not initially rendered by screen readers and similar assistive technologies.
  4. -
- -

Headers and Footers

- -

HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:

- -
    -
  1. The HTML Header Element ({{HTMLElement("header")}}) defines a page header — typically containing the logo and name of the site and possibly a horizontal menu — or section header, containing perhaps the section's heading, author name, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("header")}}. Despite its name, it is not necessarily positioned at the beginning of the page or section.
  2. -
  3. The HTML Footer Element ({{HTMLElement("footer")}}) defines a page footer — typically containing the copyright and legal notices and sometimes some links — or section footer, containing perhaps the section's publication date, license information, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("footer")}}. Despite its name, it is not necessarily positioned at the end of the page or section.
  4. -
- -

These do not create new sections in the outline, rather, they mark up content inside sections of the page.

- -

Addresses in sectioning elements

- -

The author of a document often wants to publish some contact information, such as the author's name and address. HTML4 allowed this via the {{HTMLElement("address")}} element, which has been extended in HTML5.

- -

A document can be made of different sections from different authors. A section from another author than the one of the main page is defined using the {{HTMLElement("article")}} element. Consequently, the {{HTMLElement("address")}} element is now linked to its nearest {{HTMLElement("body")}} or {{HTMLElement("article")}} ancestor.

- -

Using HTML5 elements in non-HTML5 browsers

- -

Sections and headings elements should work in most non-HTML5 browsers. Though unsupported, they don't need a special DOM interface and they only need a specific CSS styling as unknown elements are styled as display:inline by default:

- -
section, article, aside, footer, header, nav, hgroup {
-  display:block;
-}
-
- -

Of course the web developer can style them differently, but keep in mind that in a non-HTML5 browser, the default styling is different from what is expected for such elements. Also note that the {{HTMLElement("time")}} element has not been included, because the default styling for it in a non-HTML5 browser is the same as the one in an HTML5-compatible one.

- -

This method has its limitation though, as some browsers do not allow styling of unsupported elements. That is the case of the Internet Explorer (version 8 and earlier), which need a specific script to allow this:

- -
<!--[if lt IE 9]>
-  <script>
-    document.createElement("header" );
-    document.createElement("footer" );
-    document.createElement("section");
-    document.createElement("aside"  );
-    document.createElement("nav"    );
-    document.createElement("article");
-    document.createElement("hgroup" );
-    document.createElement("time"   );
-  </script>
-<![endif]-->
- -

This script means that, in the case of Internet Explorer (8 and earlier), scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they won't be displayed, which may be problematic as these elements are likely defining the structure of the whole page. That's why an explicit {{HTMLElement("noscript")}} element should be added for this case:

- -
<noscript>
-   <strong>Warning !</strong>
-   Because your browser does not support HTML5, some elements are simulated using JScript.
-   Unfortunately your browser has disabled scripting. Please enable it in order to display this page.
-</noscript>
- -

This leads to the following code to allow the support of the HTML5 sections and headings elements in non-HTML5 browsers, even for Internet Explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting:

- -
<!--[if lt IE 9]>
-  <script>
-    document.createElement("header" );
-    document.createElement("footer" );
-    document.createElement("section");
-    document.createElement("aside"  );
-    document.createElement("nav"    );
-    document.createElement("article");
-    document.createElement("hgroup" );
-    document.createElement("time"   );
-  </script>
-  <noscript>
-     <strong>Warning !</strong>
-     Because your browser does not support HTML5, some elements are created using JavaScript.
-     Unfortunately your browser has disabled scripting. Please enable it in order to display this page.
-  </noscript>
-<![endif]-->
- -

Підсумок

- -

Нові семантичні елементи, що були введені стандартом HTML5 забезпечили можливість описувати структуру документу єдиним стандартеризованим способом. They bring a big advantage for people having HTML5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. These new semantic elements are simple to use and, with very few burdens, can be made to work also in non-HTML5 browsers. Therefore they should be used without restrictions.

- -
{{HTML5ArticleTOC()}}
diff --git "a/files/uk/web/guide/\320\263\321\200\320\260\321\204\321\226\320\272\320\260/index.html" "b/files/uk/web/guide/\320\263\321\200\320\260\321\204\321\226\320\272\320\260/index.html" deleted file mode 100644 index 57af0fdbc3..0000000000 --- "a/files/uk/web/guide/\320\263\321\200\320\260\321\204\321\226\320\272\320\260/index.html" +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Графіка для Web -slug: Web/Guide/Графіка -tags: - - 2D - - 3D - - Canvas - - HTML5 - - SVG - - WebGL - - WebRTC - - Веб - - Графіка -translation_of: Web/Guide/Graphics ---- -

Сучасним сайтам і веб-додаткам потрібне відображення графіки. Статичні зображення легко зобразити використовуючи елемент {{HTMLElement("img")}}, чи налаштувати фон HTML елементів використовуючи властивість {{cssxref("background-image")}}. Ви також можете конструювати графіку на льоту, або модифікувати її після. В статтях далі сказано як це можна зробити.

- -
-
-

2D Графіка

- -
-
Canvas
-
Елемент {{HTMLElement("canvas")}} надає зручні API для малювання 2D графіки використовуючи JavaScript.
-
SVG
-
Scalable Vector Graphics (SVG) дозволяє використовувати лінії, криві, та інші геометричні фігури для рендерингу графіки. З векторів, ви можете створювати зображення які не втрачають якості при маштабуванні.
-
- -

Переглянути все...

-
- -
-

3D Графіка

- -
-
WebGL
-
Посібник для початку роботи з WebGL, API для роботи з 3D графікою в веб. Ця технологія дає вам можливість використовувати стандартний OpenGL ES в Web контенті.
-
- -

Відео

- -
-
Використання HTML5 аудіо і відео
-
Вбудовування відео і/або аудіо в веб-сторінки і керування відтворенням.
-
WebRTC
-
RTC в WebRTC означає Real-Time Communications (комунікація в реальному часі), технологія яка дозволяє передавати потокове аудіо/відео і дані між кліентами браузера (пірами).
-
-
-
diff --git a/files/uk/web/houdini/index.html b/files/uk/web/houdini/index.html new file mode 100644 index 0000000000..92be6ef3cc --- /dev/null +++ b/files/uk/web/houdini/index.html @@ -0,0 +1,87 @@ +--- +title: CSS Гудіні +slug: Web/Гудіні +translation_of: Web/Houdini +--- +

Гудіні - це набір низькорівневих API, які надають доступ до СSS движка, даючи розробникам змогу розширити СSS підключаючись до процесу створення макету та застосування стилів в процесі роботи браузерного движка. Гудіні - набір API, які дають розробникам прямий доступ  CSS Object Model (CSSOM), дозволяючи розробникам писати код який браузер може розібрати як CSS, таким чином створюючи нові СSS властивості не чекаючи щоб вони були реалізовані в браузерах.

+ +

Переваги Гудіні

+ +

Гудіні дозволяє швидше змінювати стилі  ніж при використанні JavaScript .style. Браузер розбирає CSSOM, включаючи макет, процеси відмальовування і компонування, перед застосування будьяких змін знайдених в скрипті. Крім того всі ці процеси повторюються для застосування змін з JavaScript. Гудіні не очікує на завершення першого циклу рендерингу, він включений в цей цикл, створюючи відмальовані зрозумілі стилі. Гудіні надає Гудіні дозволяє швидше змінювати стилі  ніж при використанні JavaScript .style. Браузер розбирає CSSOM, включаючи макет, процеси відмальовування і компонування, перед застосування будьяких змін знайдених в скрипті. Крім того всі ці процеси повторюються для застосування змін з JavaScript. Гудіні не очікує на завершення першого циклу рендерингу, він включений в цей цикл, створюючи відмальовані зрозумілі стилі. Гудіні надає об'єктно-орієнтований API для роботи з  CSS значеннями в JavaScript.

+ +

Гудіні CSS Типізована OM є a CSS Об'єктвною моделю з типами і методами,  показуючи значення як JavaScript об'єкт, це робить Гудіні бульш інтуїтивним ніж  HTMLElement.style маніпуляції. Кожний елемент і таблиця стилів мають карту стилів, до якої можна доступитись через його значення  StylePropertyMap.

+ +

Особливістю СSS Гудіні є  Worklet. З ворклетами, ви можете створювати модульний CSS, це потребує однієї лінійки JavaScript для імпорту налаштовуваних компоненів: без пре-процесорів, пост-процесорів або JavaScript фреймворків.

+ +
<script>
+  CSS.paintWorklet.addModule('csscomponent.js');
+</script>
+
+ +

Цей доданий модуль містить registerPaint() фунцкію, яка реєструє  повністю налаштовувані ворклетів.

+ +

 Функція CSS paint() включає в себе ім'я ворклета а також можливі додаткові параметри. Ворклет також має доступ до звичайних значеннь елемента, їх не потрібно передавати як параметри функції.

+ +
li {
+	background-image: paint(myComponent, stroke, 10px);
+    --hilights: blue;
+    --lowlights: green;
+}
+ +
+

Примітка: З великою силою приходить велика відповідальність! З Гудіні ви можете придумати свій власний макет, сітку, або реалізацію регіонів, але робити це не завжди найкраща ідея. Робоча група CSS робить багато роботи щоб упевнетись, що всі функції є продуктивними, розглядає всі можливі країні випадки і забезпечує безпеку, конфіденційність і доступність.  Коли ви почнете з СSS Гудіні, упевніться що ви дотримуєтесь цих стандартів і починайте з малого перш ніж перейти до більш амбітних проектів.

+
+ +

Гудіні API

+ +

Ніжче ви можете знайти посилання на основну довідку про API, які знаходяться під егідою Гудіні, а також посилання на туторіали.

+ + + +
+
CSS Парсер API
+
API використовуючи  CSS парсер, для парсингу CSS-подібних мов в слабо типізовані.
+
+ Для цього АPI ще не написано туторіалу чи довідки.
+
API CSS властивостей і значеннь
+
Визначає API для нових CSS властивостей. Властивості зареєстровані з цим API забезпечені синтаксисом синтаксичного аналізу, який визначає тип, поведінкою успадкування, і початкове значення.
+
+ CSS Properties and Values API reference
+ CSS Properties and Values API guide
+
+
CSS Typed OM
+
Перетворює CSSOM в значно типізований JavaScript перетворення може значно вплинути на продуктивність. CSS типізована ОМ виставляє CSS значення як JavaScript об'єкти та дозволяє ефективно керувати ним.
+
+ CSS Typed OM reference
+ CSS Typed OM guide
+
CSS Layout API 
+
+

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

+ +

Для цього АPI ще не написано туторіалу чи довідки.

+
+
CSS Painting API
+
+

Призначений для поліпшення розтяжності CSS — дозволяє розробникам писати  JavaScript функції що доволяють рисувати прямо в задній фон, границі, або зміст елементу за допомогою CSS функції paint() .
+
+ CSS Painting API reference
+ CSS Painting API guide

+
+
Worklets 
+
+

API для запуску скриптів на різних етапах потоку рендерингу незалежно від головного JavaScript середовища. Worklets концептуально схожі на Web Workers, і застосовуються для розширення движка рендерину.

+ +


+ Worklets reference

+
+
+ +

Інші теми

+ +

Схожі теми, які можуть юути цікаві, так як вони можуть бути використані в поєднанні з API Гудіні цікавими способами.

+ +
+
Composite Scrolling and Animation 
+
diff --git a/files/uk/web/html/element/header/index.html b/files/uk/web/html/element/header/index.html new file mode 100644 index 0000000000..9ed3c75dfa --- /dev/null +++ b/files/uk/web/html/element/header/index.html @@ -0,0 +1,145 @@ +--- +title:
+slug: Web/HTML/Елемент/Заголовок +tags: + - HTML + - HTML елементи +translation_of: Web/HTML/Element/header +--- +
{{HTMLRef}}
+ +

HTML <header> елемент представляє групу вступних або навігаційних елементів. Він може містити елементи заголовків, а також інші елементи, такі як логотип, форма пошуку та інше.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Content categoriesFlow content, palpable content.
Permitted contentFlow content, but with no <header> or {{HTMLElement("footer")}} descendant.
Tag omission{{no_tag_omission}}
Permitted parentsAny element that accepts flow content. Note that a <header> element must not be a descendant of an {{HTMLElement("address")}}, {{HTMLElement("footer")}} or another {{HTMLElement("header")}} element.
Permitted ARIA roles{{ARIARole("group")}}, {{ARIARole("presentation")}}
DOM interface{{domxref("HTMLElement")}}
+ +

Зауваження до використання

+ +

The <header> element is not sectioning content and therefore does not introduce a new section in the outline. That said, a header element is intended to usually contain the surrounding section's heading (an h1h6 element), but this is not required.

+ +

Атрибути

+ +

This element only includes the global attributes.

+ +

Приклад

+ +
<header>
+  <h1>Main Page Title</h1>
+  <img src="mdn-logo-sm.png" alt="MDN logo">
+</header>
+
+ +

Main Page Title

+ +

MDN

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-header-element', '<header>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'sections.html#the-header-element', '<header>')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}9.011.104.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.2{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}9.011.05.0
+
+ +

See also

+ + diff --git a/files/uk/web/html/element/html/index.html b/files/uk/web/html/element/html/index.html new file mode 100644 index 0000000000..22489d772f --- /dev/null +++ b/files/uk/web/html/element/html/index.html @@ -0,0 +1,169 @@ +--- +title: +slug: Web/HTML/Елемент/html +tags: + - Корінь + - Структура +translation_of: Web/HTML/Element/html +--- +

{{HTMLRef}}

+ +

HTML-елемент <html> являє собою корінь HTML-документа. Решта елементів мають бути його нащадками.

+ +

Оскільки <html> є першим (за винятком коментарів) елементом документа, він зветься кореневим елементом. І хоча цей тег може бути відсутнім для {{glossary("HTML")}}, в {{glossary("XHTML")}} він має бути відкритий і закритий явно.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Категорії вмістуВідсутні.
Дозволений вмістОдин елемент {{HTMLElement("head")}} та один (наступний за ним) елемент {{HTMLElement("body")}}.
Обов'язковість тегів +

Початковий тег можна опустити, якщо перша річ всередині елементу <html> — не коментар. Кінцевий тег можна опустити тоді, коли одразу після елементу <html> немає коментаря, і він містить елемент {{HTMLElement("body")}}, що має або вміст (непустий), або початковий тег.

+
Дозволені пращуриЯк кореневий елемент документа, або як піддокумент складного документа там, де це дозволено.
Інтерфейс DOM{{domxref("HTMLHtmlElement")}}
+ +

Атрибути

+ +

Цей елемент має глобальні атрибути.

+ +
+
{{htmlattrdef("manifest")}} {{obsolete_inline}}
+
Вказує URI manifest-файлу, що позначає ресурси, які підлягають локальному кешуванню. Детальніше див. Using the application cache.
+
{{htmlattrdef("version")}} {{obsolete_inline}}
+
Вказує версію HTML {{glossary("DTD", "Document Type Definition")}}  цього документа. Цей атрибут визнано застарілим, вживайте !DOCTYPE замість нього.
+
{{htmlattrdef("xmlns")}} 
+
Вказує простір імен (XML) документа. Типове значення "http://www.w3.org/1999/xhtml". Для XHTML то обов'язковий атрибут, а для HTML може бути відсутнім.
+
+ +

Приклад

+ +
+

Використаний в прикладі  {{glossary("DOCTYPE")}} вказує на {{glossary("HTML5")}}.

+
+ +
<!DOCTYPE html>
+<html>
+  <head>...</head>
+  <body>...</body>
+</html>
+
+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'semantics.html#the-html-element', '<html>')}}{{Spec2('HTML5 W3C')}}Додано підтримку атрибута manifest (згодом визнаний застарілим).
+ Атрибут version визнано застарілим.
{{SpecName('HTML4.01', 'struct/global.html#h-7.3', '<html>')}}{{Spec2('HTML4.01')}}Атрибут version визнано застарілим.
+ +

Підтримка браузерами

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
manifest{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
manifest{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Див. також

+ + diff --git a/files/uk/web/html/element/iframe/index.html b/files/uk/web/html/element/iframe/index.html new file mode 100644 index 0000000000..fc5b06a037 --- /dev/null +++ b/files/uk/web/html/element/iframe/index.html @@ -0,0 +1,260 @@ +--- +title: '