Margin left css что это

от admin

margin-left

In this example there are three blocks, styled identically except for their margin-left values:

  • The first one has a margin-left of 2 centimeters, meaning that it is pushed over to the right by 2cm.
  • The second one has no margin-left of its own, to indicate the default position of the blocks.
  • The bottom block has a margin-left of -10% set on it, meaning that it is pushed over to the left by 10% of the parent element’s width.

CSS applied to the HTML shown in the first example.

Usage

  • When calculating the height and width of an element, DO NOT include the margins in your calculations (i.e. include everything else: content area, padding, and border). However, DO include margin size when calculating available space within an element’s containing element.
  • When two margins collide, for example when one block level element has a right margin set, and a floated element directly to the right of it has a left margin set, the larger of the two margins remains, and the smaller one collapses and disappears.
  • Margins are always transparent.

Best Practices

  • When possible, use margin shorthand (i.e. ) to specify margin-widths rather than writing out each margin’s specifications as this clutters code and makes it difficult to read. Use margin-bottom if there is a specific reason to call attention to it (e.g. one element has a different bottom margin than the rest in its class, etc.).

Notes

You can specify possible length values relative to the height of the element’s font ( em ) or the height of the letter “x” ( ex ). In Microsoft Internet Explorer 3.0, the specified margin value is added to the default value of the object. In Microsoft Internet Explorer 4.0 and later, the margin value is absolute. The margin properties do not work with the td and tr objects in Internet Explorer 4.0, but they do work in Internet Explorer 3.0. To set margins in the cell for Internet Explorer 4.0 and later, apply the margin to an object, such as div or p, within the td. This property applies to inline elements, starting with Microsoft Internet Explorer 5.5. With earlier versions of Windows Internet Explorer, inline elements must have an absolute position or layout to use this property. Element layout is set by providing a value for the height property or the width property. Negative margins are supported, except for top and bottom margins on inline objects.

CSS margin-left Property

The margin-left property is used to define how much the left margin of the element will be set.

There are some rare situations when width, margin-left , border, padding, the content area and margin-right are defined. When it happens, the margin-left will be ignored and it will be set as if the auto value is defined.

The margin-left property is defined as the keyword <auto>, <percentage> or a <length>. Its value may be negative, positive or zero.

[ В закладки ] CSS: использование внутренних и внешних отступов

Если несколько элементов веб-страницы расположены близко друг к другу, то у пользователей возникает такое ощущение, что у этих элементов есть что-то общее. Группировка элементов помогает пользователю понять их взаимосвязь благодаря оценке расстояния между ними. Если бы все элементы были бы расположены на одинаковом расстоянии друг от друга, пользователю сложно было бы, просматривая страницу, узнать о том, какие из них связаны друг с другом, а какие — нет.


Эта статья посвящена всему, что нужно знать о настройке расстояний между элементами и о настройке внутренних пространств элементов. В частности, речь пойдёт о том, в каких ситуациях стоит использовать внутренние отступы (padding), а в каких — внешние (margin).

Виды расстояний в CSS

Расстояния между элементами и их частями, настраиваемые средствами CSS, бывают двух видов. Они, по отношению к элементу, делятся на внутренние и внешние. Представим, что у нас имеется элемент. Если внутри него имеется некое расстояние между какими-то его частями, то это — внутренний отступ. Если же речь идёт о расстоянии между отдельными элементами — то это внешний отступ.

Внутреннее пространство и внешнее пространство

В CSS расстояние между элементами и их составными частями можно настраивать так:

Свойство padding использовано здесь для настройки внутреннего отступа, а свойство margin — для настройки внешнего отступа. Всё очень просто. Правда? Но настройка расстояний в CSS может серьёзно усложниться в том случае, если работают с компонентами, имеющими множество мелких составных частей и дочерних элементов.

▍Свойство margin — внешний отступ

Свойство margin используется для настройки расстояния между отдельными элементами. Например, в предыдущем примере использовано CSS-свойство margin-bottom: 1rem для добавления вертикального расстояния между двумя элементами, расположенными друг над другом.

Внешний отступ можно настраивать для четырёх сторон элемента (top, right, bottom, left — верхней, правой, нижней, левой). Поэтому, прежде чем переходить к примерам и к обсуждениям разных способов настройки расстояний, важно пролить свет на некоторые базовые концепции.

▍Схлопывание внешних отступов

Если описать понятие «схлопывание внешних отступов» простыми словами, то можно сказать, что это происходит в том случае, если два элемента, расположенных друг над другом, имеют внешние отступы, и при этом отступ одного из них больше, чем отступ другого. В таком случае будет использован больший отступ, а меньший будет проигнорирован.

Побеждает больший отступ

На вышеприведённой схеме у верхнего элемента настроено свойство margin-bottom , а у нижнего — свойство margin-top . Вертикальное расстояние между элементами соответствует большему из этих отступов.

Для того чтобы избежать этой проблемы, рекомендуется настраивать во всех элементах одни и те же отступы (как описано здесь). И вот ещё один интересный факт. Ресурс CSS Tricks устроил голосование по поводу использования свойств margin-bottom и margin-top . Как оказалось, свойство margin-bottom победило, взяв 61% голосов.

Вот как решается эта проблема:

Использование CSS-селектора :not позволяет легко удалить внешний отступ у последнего дочернего элемента для того чтобы избавиться от ненужного пространства между элементами.

→ Вот демонстрация работы с внешними отступами

Ещё один пример, связанный со схлопыванием внешних отступов, связан с дочерними и родительскими элементами. Предположим, имеется следующий HTML-код:

Вот как выглядит результат визуализации всего этого.

Дочерний и родительский элементы

Обратите внимание на то, что дочерний элемент упирается в верхнюю часть родительского элемента. Это — результат схлопывания их внешних отступов. По данным W3C, есть несколько вариантов решения этой проблемы:

  • Добавление свойства border к родительскому элементу.
  • Установка свойства display дочернего элемента в значение inline-block .

Настройка верхнего внутреннего отступа родительского элемента

▍Отрицательный внешний отступ

Отрицательное значение можно использовать для любых внешних отступов. В некоторых случаях этот приём оказывается весьма полезным. Взглянем на следующий рисунок.

Результаты настройки свойства padding родительского элемента

У родительского элемента имеется свойство padding: 1rem . Это приводит к тому, что у дочернего элемента появляются смещения сверху, слева и справа. Но дочерний элемент должен прилегать к границам родительского элемента. Добиться этого помогут отрицательные внешние отступы.

Вот что получилось в результате такой стилизации.

Отрицательные внешние отступы дочернего элемента помогают добиться желаемого эффекта

Если тема отрицательных внешних отступов вам интересна — рекомендую эту статью.

▍Свойство padding — внутренние отступы

Как уже было сказано, свойство padding позволяет управлять пространством внутри элемента. Цель применения этого свойства зависит от того, в какой ситуации оно используется.

Например, его можно использовать для увеличения пространства вокруг ссылок. Это приводит к увеличению кликабельного пространства ссылок.

Зелёным цветом выделен внутренний отступ

▍Ситуации, в которых свойство padding не работает

Важно отметить, что вертикальные внутренние отступы не работают с элементами, имеющими свойство display: inline . Например, это элементы <span> и <a> . Если настроить свойство padding такого элемента, такая настройка на данный элемент не подействует. Это — всего лишь дружеское напоминание о том, что у inline-элементов нужно менять свойство display :

Пространство между элементами CSS Grid-макета

В модели CSS Grid можно легко настраивать расстояние между столбцами и строками, используя свойство grid-gap . Это — сокращённое название свойства, задающего расстояния между столбцами и строками.

Расстояния между столбцами и строками

Полная запись этих свойств выглядит так:

Пространство между элементами CSS Flexbox-макета

Есть одно свойство, предложенное для Grid- и Flexbox-макетов. Это — свойство gap . В настоящее время его поддерживает лишь Firefox.

Более того, это свойство нельзя использовать с CSS @supports для определения того, поддерживается ли оно, и для принятия соответствующих решений, основываясь на этом. Если это свойство вам нравится — голосуйте за добавление его в Chrome.

Позиционирование элементов в CSS

Возможно, позиционирование элементов нельзя напрямую отнести к способам настройки расстояния между ними, но в некоторых случаях позиционирование играет определённую роль. Например, если есть абсолютно позиционированный дочерний элемент, который нужно расположить в 16px от левого и верхнего краёв родительского элемента.

Рассмотрим следующий пример. Есть карточка, на которой имеется иконка, которую нужно расположить на некотором расстоянии от верхнего и левого краёв родительского элемента. Для достижения этого эффекта можно воспользоваться следующим стилем:

Зелёным выделено расстояние между границами родительского и дочернего элементов

Сценарии использования и практические примеры

В этом разделе мы рассмотрим сценарии использования средств настройки расстояний между элементами. Нечто подобное вполне может встретиться вам в повседневной работе с CSS.

▍Компонент-заголовок

Компонент — заголовок, у которого настроено следующее: отступ слева и справа, пространство вокруг логотипа, пространство вокруг навигационного элемента, расстояние между навигационным элементом и именем пользователя

В данном случае в компоненте-заголовке имеется логотип, область навигации, и область, в которой выводятся сведения о профиле пользователя. Можете догадаться о том, как должен выглядеть код стилизации такого элемента? Вот, чтобы было легче, схематичная разметка такого элемента:

Внутренние и внешние отступы

Слева и справа используются внутренние отступы. Их цель заключается в том, чтобы содержимое заголовка не прижималось бы к его краям.

При настройке навигационных ссылок нужно учитывать то, что у каждой из них должно быть достаточно внутреннего пространства по вертикали и по горизонтали. Благодаря этому их кликабельная область будет достаточно большой, что улучшит доступность проекта.

Если же говорить о расстоянии между элементами, то тут можно использовать свойство margin , либо — можно изменить свойство display элементов <li> на inline-block . Благодаря этому добавляется небольшое пространство между элементами, лежащими на одном уровне, из-за того, что такие элементы рассматриваются как символы.

И наконец, у имени пользователя и аватара есть левый внешний отступ.

Обратите внимание на то, что если вы создаёте многоязычный сайт, рекомендовано в подобной ситуации использовать логические CSS-свойства:

Расстояния до и после разделителя неодинаковы

Обратите внимание на то, что расстояния до и после разделителя неодинаковы. Причина этого заключается в том, что у навигационного блока не задана ширина. Вместо этого тут настроены лишь внутренние отступы. В результате ширина навигационных элементов зависит от их содержимого. Вот варианты решения этой проблемы:

  • Настройка минимальной ширины для навигационных элементов.
  • Увеличение горизонтального внутреннего отступа.
  • Добавление в левой части разделителя дополнительного внешнего отступа.

▍Расстояния в сеточных макетах — CSS Flexbox

Сеточные макеты — это то место, где часто применяются технологии настройки расстояния между элементами. Рассмотрим следующий пример.

Сеточный макет

Нам нужно настроить расстояние между строками и столбцами таблицы. Вот разметка:

Обычно я предпочитаю держать компоненты в инкапсулированном состоянии и избегаю настройки их внешних отступов. По этой причине у меня есть элемент grid_item , в котором будет располагаться элемент-карточка.

Благодаря этому CSS-коду в каждой строке будет четыре карточки. Вот один из возможных способов настройки расстояния между ними:

Благодаря использованию CSS-функции calc() внешний отступ вычитается из flex-basis . Как видите, это не такое уж и простое решение. Я, на самом деле, предпочитаю следующее:

  • Настроить у элемента сетки свойство padding-left .
  • Настроить у родительского элемента отрицательный внешний отступ margin-left с тем же значением, что и у padding-left .

Причина, по которой я использовал здесь отрицательное значение для margin-left , заключается в том, что у первой карточки есть свойство padding-left , которое, в реальности, не нужно. В результате я перемещаю элемент-обёртку влево и избавляюсь от ненужного пространства.

Ещё одна похожая идея заключается в использовании внутренних отступов и отрицательных внешних отступов. Вот — пример с сайта Facebook.

Внутренние и внешние отступы

Вот CSS-код, иллюстрирующий эту идею:

▍Расстояния в сеточных макетах — CSS Grid

А теперь — самое приятное! В макетах, основанных на CSS Grid, расстояния между элементами очень удобно настраивать, используя свойство grid-gap . Кроме того, можно не беспокоиться о ширине элементов и о нижних внешних границах. CSS Grid-макет берёт на себя заботы обо всём этом.

Вот и всё. Полагаю, никто не станет спорить с тем, что настройка Grid-макетов легче и понятнее, чем настройка Flexbox-макетов.

▍Настройка расстояния между элементами только тогда, когда это необходимо

В Grid-макетах мне чрезвычайно нравится то, что свойство grid-gap применяется лишь в том случае, когда между элементами должно быть некое расстояние. Взглянем на следующий макет.

Макет сетки, в которой элементы в мобильной среде расположены вертикально, а в настольной — горизонтально

Есть раздел сайта с двумя карточками. Мне нужно, чтобы они были бы разделены и в мобильной среде, при вертикальном расположении карточек, и в настольной, при горизонтальном их расположении. Без CSS Grid такой гибкости макета достичь невозможно. Взгляните на следующий код:

Не очень-то удобно. Правда? А как насчёт следующего стиля?

Дело сделано! И устроено всё значительно проще.

▍Работа с нижним внешним отступом

Предположим, что у нас имеются следующие компоненты, расположенные друг над другом. У каждого из них настроен нижний внешний отступ.

Набор компонентов, расположенных горизонтально

Обратите внимание на то, что нижний внешний отступ имеется и у последнего элемента. А это неправильно, так как отступы должны присутствовать лишь между элементами.

Исправить эту проблему можно, прибегнув к одному из решений, которые мы сейчас разберём.

Решение №1: CSS-селектор :not
Решение №2: комбинация соседних элементов одного уровня
Анализ решений

Хотя решение №1 кажется более привлекательным, у него есть следующие недостатки:

  • Оно приводит к проблемам с CSS-специфичностью. Его нельзя переопределить до тех пор, пока используется селектор :not .
  • Оно неприменимо в случаях, когда имеется более чем один столбец элементов. Это проиллюстрировано ниже.

Два столбца элементов и проблема решения №1

Если говорить о решении №2, то его применение не приводит к возникновению проблем со специфичностью. Правда, это решение тоже подходит лишь в тех случаях, когда речь идёт об одном столбце элементов.

В этой ситуации лучше всего прибегнуть к решению по удалению ненужного пространства путём добавления отрицательного внешнего отступа к родительскому элементу:

Здесь происходит следующее. Благодаря такой настройке элемент смещается вниз на расстояние, равное заданному внешнему отступу. Но тут следует проявлять осторожность и не задать такой внешний отступ при использовании которого элементы бы перекрылись.

▍Компонент-карточка

Теперь хочу подробно обсудить настройки компонентов-карточек. Возможно, в итоге у меня получится целая книга об этом. Здесь же я рассмотрю универсальный паттерн настройки карточек и расскажу о том, как ими управлять.

Компонент-карточка (если вам захотелось есть — извиняюсь)

Подумайте о том, где именно в этой карточке используется настройка расстояний между элементами и их частями. Вот мой ответ на этот вопрос.

Внутренние и внешние отступы

Вот стиль класса card__content :

Благодаря установленному здесь внутреннему отступу будет настроено смещение для всех дочерних элементов. Затем настраиваем внешние отступы:

Настраивая разделение оценки и сведений, я использовал границу:

Но тут мы сталкиваемся с проблемой! Граница не привязана к краям, что происходит из-за того, что у родительского элемента с классом card__content настроен внутренний отступ.

Разделитель не привязан к краю

Вы, пожалуй, уже догадались о том, что нам тут помогут отрицательные отступы:

Но и тут снова что-то пошло не так. Теперь текст прилип к краю карточки.

Разделитель в норме, но содержимое карточки расположено неправильно

Для того чтобы решить эту проблему, нужно настроить левый и правый внутренние отступы для содержимого карточки.

Карточка настроена так, как нужно

▍Содержимое статей

Я уверен в том, что то, о чём мы будем тут говорить, представляет собой очень и очень сильно распространённую ситуацию. Дело тут в том, что содержимое статей обычно поступает на страницы из CMS (Content Management System — система управления контентом), или генерируется автоматически на основе Markdown-файлов. Здесь нельзя указывать классы элементов.

Рассмотрим следующий пример, в котором представлена разметка, содержащая смесь из заголовков, абзацев и изображений.

Для того чтобы привести это всё к приличному виду, расстояния между элементами должны быть единообразными и должны использоваться ответственно. Работая над данным примером я позаимствовал некоторые стили с type-scale.com.

Вот схема страницы с текстом статьи.

Схема страницы и применение свойств margin-top и margin-bottom

Если за элементом <p> следует заголовок, например — заголовок Types of Spacing , то свойство margin-bottom элемента <p> будет проигнорировано. Это, как вы можете догадаться, является следствием схлопывания внешних отступов.

▍Внешние отступы, применяемые в зависимости от обстоятельств

Взгляните на следующий макет.

Элементы в нормальном состоянии и в ситуации нехватки места

Элементы не очень хорошо выглядят в том случае, когда они находятся друг к другу слишком близко. Я создал этот макет с использованием Flexbox. Эта методика называется «Alignment Shifting Wrapping» (Выравнивание Сдвиг Перенос). Я узнал о её названии отсюда.

В результате применения этой методики осуществляется перенос строк в том случае, если область просмотра меньше определённого предела. Вот как это выглядит.

Дочерние элементы находятся на новых строках

Здесь нужно разобраться с промежуточной ситуацией, в которой два элемента всё ещё находятся рядом друг с другом, но расстояние между ними равно нулю. В таком случае я предпочитаю прибегать к свойству margin-right , что не даёт элементам касаться друг друга и ускоряет срабатывание flex-wrap .

Элементы не касаются друг друга

▍CSS-свойство writing-mode

Сначала процитируем MDN: «Свойство writing-mode устанавливает горизонтальное или вертикальное положение текста, а также — направление блока».

Размышляли когда-нибудь о том, как должны вести себя внешние отступы в том случае, когда они используются с элементом, свойство writing-mode которого отличается от стандартного? Рассмотрим следующий пример.

Карточка с вертикальным заголовком

Заголовок повёрнут на 90 градусов. Между ним и изображением должно быть пустое пространство. Как оказалось, свойство margin-right отлично показывает себя при разных значениях свойства writing-mode .

Полагаю, мы рассмотрели достаточно сценариев использования отступов. Теперь рассмотрим некоторые интересные концепции.

Инкапсуляция компонентов

В больших дизайн-системах содержится множество компонентов. Логично ли будет настраивать их внешние отступы?

Рассмотрим следующий пример.

Где нужно настраивать расстояния между кнопками? Нужно ли настраивать какие-то свойства левой или правой кнопки? Может, можно воспользоваться комбинацией соседних элементов одного уровня?

Ничего хорошего в этом нет. А что если имеется лишь одна кнопка? А как это будет работать на мобильном устройстве, в том случае, когда кнопки расположены по вертикали, а не по горизонтали? В общем, тут перед нами встаёт множество сложных вопросов.

▍Использование абстрагированных компонентов

Решением вышеозначенных проблем является применение абстрагированных компонентов, которые используются для размещения в них других компонентов. Это, как сказано здесь, что-то вроде перемещения ответственности за управление отступами на родительский элемент. Переосмыслим предыдущий пример в свете этой идеи.

Родительские и дочерние компоненты

Обратите внимание на то, что тут присутствуют элементы-обёртки. Каждая кнопка обладает собственной обёрткой.

Вот и всё! И более того — эту концепцию легко применить к любому JavaScript-фреймворку. Например:

А используемый JS-инструмент должен поместить каждый элемент в собственную обёртку.

Компоненты, используемые в качестве разделителей

Если вы сомневаетесь в том, что прочли заголовок правильно — не сомневайтесь. Речь идёт о компонентах, используемых в качестве разделителей. В частности, тут я ссылаюсь на эту статью, в которой обсуждается концепция, в соответствии с которой избегают использования внешних отступов и применяют вместо них компоненты-разделители.

Представим, что в некоем разделе сайта нужен левый внешний отступ размером 24px . При этом к отступу выдвигаются следующие требования:

  • Внешний отступ не должен настраиваться непосредственно у компонента, так как он является частью уже созданной дизайн-системы.
  • Отступ должен быть гибким. На одной странице он может иметь размер X , а на другой — размер Y .

Элемент-разделитель в дизайне Facebook

Здесь в качестве элемента-разделителя используется <div> с встроенным стилем width: 16px . Его единственная цель — добавление пустого пространства между левым элементом и элементом-контейнером.

Вот цитата из данной методички по React: «Но в реальном мире мы нуждаемся в пространствах, задаваемых за пределами компонентов, для компоновки компонентов в страницы и сцены. Именно здесь настройки внешних отступов и пробираются в код компонентов для настройки расстояний между компонентами при их компоновке».

Я с этим согласен. В большой дизайн-системе нерациональным будет добавление к компонентам внешних отступов. Это, в результате, приведёт к не очень хорошо выглядящему коду.

▍Проблемы компонентов-разделителей

Теперь, когда вы ознакомились с идеей компонентов-разделителей, давайте поговорим о некоторых проблемах, вполне ожидаемых, которые могут возникнуть при работе с ними. Вот вопросы об этом, над которыми я размышлял:

  • Как компонент-разделитель занимает место в родительском компоненте? Как он ведёт себя в горизонтальных и вертикальных макетах? Например — как такой компонент разделит компоненты, расположенные вертикально и горизонтально?
  • Нужно ли стилизовать эти компоненты, основываясь на свойстве display компонента-родителя (Flexbox, Grid)?

▍Размеры компонентов-разделителей

Можно создать компонент-разделитель, принимающий различные параметры. Я — не JavaScript-разработчик, но думаю, что это то, что называется «свойствами» (props). Рассмотрим следующий пример, взятый отсюда.

Имеется компонент-разделитель, расположенный между компонентами Header и Section .

А вот — несколько иная ситуация. Тут разделитель используется для создания автоматически настраиваемого расстояния между логотипом (компонентом Logo ) и областью навигации, представленной компонентами Link .

Может показаться, что реализовать такой разделитель средствами CSS очень просто, и что для этого достаточно воспользоваться конструкцией justify-content: space-between . Но что если дизайн понадобится поменять? В таком случае придётся менять стилизацию.

Взгляните на следующий пример. Выглядит ли этот код гибким?

В этом случае стилизация нуждается в изменении.

В том, что касается размеров, можно сказать, что размер разделителя может быть настроен на основе размеров родительского элемента. В вышеприведённом случае, возможно, есть смысл создать свойство grow , которое в CSS устанавливается в значение flex-grow: 1 .

▍Использование псевдоэлементов

Ещё одна идея, которая пришла мне в голову, заключается в использовании псевдоэлементов для создания разделителей.

Может быть, у нас есть возможность сделать разделителем псевдоэлемент, а не использовать для этого отдельный элемент? Например:

До сих пор я не пользовался компонентами-разделителями в своих проектах. Но я ищу сценарии, в которых они могли бы мне пригодиться.

Математические CSS-функции min(), max(), clamp()

Можно ли сделать отступы динамическими? Например, можно ли воспользоваться таким отступом, минимальный и максимальный размер которого зависит от ширины области просмотра? Я могу ответить на этот вопрос положительно. CSS-функции, в соответствии с данными CanIUse, поддерживаются всеми ведущими браузерами.

Вспомним о Grid-макетах и поговорим о том, как в них может использоваться динамическая настройка отступов.

Конструкция min(2vmax, 32px) означает следующее: использовать расстояние, равное 2vmax , но не превышающее 32px .

→ Вот видеодемонстрация такого макета

Такая гибкость поистине удивительна. Она даёт нам множество возможностей по созданию динамических и гибких макетов веб-страниц.

Итоги

В этом материале мы рассмотрели особенности настройки расстояний между элементами веб-страниц с использованием CSS и поговорили об управлении внутренним пространством элементов. Надеемся, вам пригодится то, о чём вы сегодня узнали.

Уважаемые читатели! Какими средствами для настройки расстояния между элементами веб-страниц вы пользуетесь чаще всего?

Margin left css что это

Contents

Note: Several sections of this specification have been updated by other specifications. Please, see «Cascading Style Sheets (CSS) — The Official Definition» in the latest CSS Snapshot for a list of specifications and the sections they replace.

The CSS Working Group is also developing CSS level 2 revision 2 (CSS 2.2).

The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model.

Each box has a (e.g., text, an image, etc.) and optional surrounding , , and areas; the size of each area is specified by properties defined below. The following diagram shows how these areas relate and the terminology used to refer to pieces of margin, border, and padding:

Image illustrating the relationship between content, padding, borders, and margins.[D]

The margin, border, and padding can be broken down into top, right, bottom, and left segments (e.g., in the diagram, «LM» for left margin, «RP» for right padding, «TB» for top border, etc.).

The perimeter of each of the four areas (content, padding, border, and margin) is called an «edge», so each box has four edges:

content edge or inner edge The content edge surrounds the rectangle given by the width and height of the box, which often depend on the element’s rendered content. The four content edges define the box’s . padding edge The padding edge surrounds the box padding. If the padding has 0 width, the padding edge is the same as the content edge. The four padding edges define the box’s . border edge The border edge surrounds the box’s border. If the border has 0 width, the border edge is the same as the padding edge. The four border edges define the box’s . margin edge or outer edge The margin edge surrounds the box margin. If the margin has 0 width, the margin edge is the same as the border edge. The four margin edges define the box’s .

Each edge may be broken down into a top, right, bottom, and left edge.

The dimensions of the content area of a box — the and — depend on several factors: whether the element generating the box has the ‘width’ or ‘height’ property set, whether the box contains text or other boxes, whether the box is a table, etc. Box widths and heights are discussed in the chapter on visual formatting model details.

The background style of the content, padding, and border areas of a box is specified by the ‘background’ property of the generating element. Margin backgrounds are always transparent.

This example illustrates how margins, padding, and borders interact. The example HTML document:

results in a document tree with (among other relationships) a UL element that has two LI children.

The first of the following diagrams illustrates what this example would produce. The second illustrates the relationship between the margins, padding, and borders of the UL elements and those of its children LI elements. (Image is not to scale.)

Image illustrating how parent and child margins, borders, and padding relate.[D]

  • The content width for each LI box is calculated top-down; the containing block for each LI box is established by the UL element.
  • The margin box height of each LI box depends on its content height, plus top and bottom padding, borders, and margins. Note that vertical margins between the LI boxes collapse.
  • The right padding of the LI boxes has been set to zero width (the ‘padding’ property). The effect is apparent in the second illustration.
  • The margins of the LI boxes are transparent — margins are always transparent — so the background color (yellow) of the UL padding and content areas shines through them.
  • The second LI element specifies a dashed border (the ‘border-style’ property).

8.3 Margin properties: ‘margin-top’ , ‘margin-right’ , ‘margin-bottom’ , ‘margin-left’ , and ‘margin’

Margin properties specify the width of the margin area of a box. The ‘margin’ shorthand property sets the margin for all four sides while the other margin properties only set their respective side. These properties apply to all elements, but vertical margins will not have any effect on non-replaced inline elements.

The properties defined in this section refer to the <margin-width> value type, which may take one of the following values:

<length> Specifies a fixed width. <percentage> The percentage is calculated with respect to the width of the generated box’s containing block. Note that this is true for ‘margin-top’ and ‘margin-bottom’ as well. If the containing block’s width depends on this element, then the resulting layout is undefined in CSS 2.1. auto See the section on calculating widths and margins for behavior.

Negative values for margin properties are allowed, but there may be implementation-specific limits.

These properties have no effect on non-replaced inline elements.

These properties set the top, right, bottom, and left margin of a box.

The ‘margin’ property is a shorthand property for setting ‘margin-top’ , ‘margin-right’ , ‘margin-bottom’ , and ‘margin-left’ at the same place in the style sheet.

If there is only one component value, it applies to all sides. If there are two values, the top and bottom margins are set to the first value and the right and left margins are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.

The last rule of the example above is equivalent to the example below:

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to , and the resulting combined margin is called a .

  • Margins of the root element’s box do not collapse.
  • If the top and bottom margins of an element with clearance are adjoining, its margins collapse with the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block.

Horizontal margins never collapse.

  • both belong to in-flow block-level boxes that participate in the same block formatting context
  • no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes (see 9.4.2) are ignored for this purpose.)
  • both belong to vertically-adjacent box edges, i.e. form one of the following pairs:
    • top margin of a box and top margin of its first in-flow child
    • bottom margin of box and top margin of its next in-flow following sibling
    • bottom margin of a last in-flow child and bottom margin of its parent if the parent has ‘auto’ computed height
    • top and bottom margins of a box that does not establish a new block formatting context and that has zero computed ‘min-height’ , zero or ‘auto’ computed ‘height’ , and no in-flow children

    A collapsed margin is considered adjoining to another margin if any of its component margins is adjoining to that margin.

    Note. Adjoining margins can be generated by elements that are not related as siblings or ancestors.

    • Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).
    • Margins of elements that establish new block formatting contexts (such as floats and elements with ‘overflow’ other than ‘visible’) do not collapse with their in-flow children.
    • Margins of absolutely positioned boxes do not collapse (not even with their in-flow children).
    • Margins of inline-block boxes do not collapse (not even with their in-flow children).
    • The bottom margin of an in-flow block-level element always collapses with the top margin of its next in-flow block-level sibling, unless that sibling has clearance.
    • The top margin of an in-flow block element collapses with its first in-flow block-level child’s top margin if the element has no top border, no top padding, and the child has no clearance.
    • The bottom margin of an in-flow block box with a ‘height’ of ‘auto’ and a ‘min-height’ of zero collapses with its last in-flow block-level child’s bottom margin if the box has no bottom padding and no bottom border and the child’s bottom margin does not collapse with a top margin that has clearance.
    • A box’s own margins collapse if the ‘min-height’ property is zero, and it has neither top or bottom borders nor top or bottom padding, and it has a ‘height’ of either 0 or ‘auto’, and it does not contain a line box, and all of its in-flow children’s margins (if any) collapse.

    When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins’ widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

    • If the element’s margins are collapsed with its parent’s top margin, the top border edge of the box is defined to be the same as the parent’s.
    • Otherwise, either the element’s parent is not taking part in the margin collapsing, or only the parent’s bottom margin is involved. The position of the element’s top border edge is the same as it would have been if the element had a non-zero bottom border.

    Note that the positions of elements that have been collapsed through have no effect on the positions of the other elements with whose margins they are being collapsed; the top border edge position is only required for laying out descendants of these elements.

    8.4 Padding properties: ‘padding-top’ , ‘padding-right’ , ‘padding-bottom’ , ‘padding-left’ , and ‘padding’

    The padding properties specify the width of the padding area of a box. The ‘padding’ shorthand property sets the padding for all four sides while the other padding properties only set their respective side.

    The properties defined in this section refer to the <padding-width> value type, which may take one of the following values:

    <length> Specifies a fixed width. <percentage> The percentage is calculated with respect to the width of the generated box’s containing block, even for ‘padding-top’ and ‘padding-bottom’ . If the containing block’s width depends on this element, then the resulting layout is undefined in CSS 2.1.

    Unlike margin properties, values for padding values cannot be negative. Like margin properties, percentage values for padding properties refer to the width of the generated box’s containing block.

    These properties set the top, right, bottom, and left padding of a box.

    The ‘padding’ property is a shorthand property for setting ‘padding-top’ , ‘padding-right’ , ‘padding-bottom’ , and ‘padding-left’ at the same place in the style sheet.

    If there is only one component value, it applies to all sides. If there are two values, the top and bottom paddings are set to the first value and the right and left paddings are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.

    The surface color or image of the padding area is specified via the ‘background’ property:

    The example above specifies a ‘1em’ vertical padding ( ‘padding-top’ and ‘padding-bottom’ ) and a ‘2em’ horizontal padding ( ‘padding-right’ and ‘padding-left’ ). The ’em’ unit is relative to the element’s font size: ‘1em’ is equal to the size of the font in use.

    The border properties specify the width, color, and style of the border area of a box. These properties apply to all elements.

    Note. Notably for HTML, user agents may render borders for certain user interface elements (e.g., buttons, menus, etc.) differently than for «ordinary» elements.

    8.5.1 Border width: ‘border-top-width’ , ‘border-right-width’ , ‘border-bottom-width’ , ‘border-left-width’ , and ‘border-width’

    The border width properties specify the width of the border area. The properties defined in this section refer to the <border-width> value type, which may take one of the following values:

    thin A thin border. medium A medium border. thick A thick border. <length> The border’s thickness has an explicit value. Explicit border widths cannot be negative.

    The interpretation of the first three values depends on the user agent. The following relationships must hold, however:

    Furthermore, these widths must be constant throughout a document.

    These properties set the width of the top, right, bottom, and left border of a box.

    This property is a shorthand property for setting ‘border-top-width’ , ‘border-right-width’ , ‘border-bottom-width’ , and ‘border-left-width’ at the same place in the style sheet.

    If there is only one component value, it applies to all sides. If there are two values, the top and bottom borders are set to the first value and the right and left are set to the second. If there are three values, the top is set to the first value, the left and right are set to the second, and the bottom is set to the third. If there are four values, they apply to the top, right, bottom, and left, respectively.

    In the examples below, the comments indicate the resulting widths of the top, right, bottom, and left borders:

    8.5.2 Border color: ‘border-top-color’ , ‘border-right-color’ , ‘border-bottom-color’ , ‘border-left-color’ , and ‘border-color’

    The border color properties specify the color of a box’s border.

    The ‘border-color’ property sets the color of the four borders. Values have the following meanings:

    <color> Specifies a color value. transparent The border is transparent (though it may have width).

    The ‘border-color’ property can have from one to four component values, and the values are set on the different sides as for ‘border-width’ .

    If an element’s border color is not specified with a border property, user agents must use the value of the element’s ‘color’ property as the computed value for the border color.

    In this example, the border will be a solid black line.

    8.5.3 Border style: ‘border-top-style’ , ‘border-right-style’ , ‘border-bottom-style’ , ‘border-left-style’ , and ‘border-style’

    The border style properties specify the line style of a box’s border (solid, double, dashed, etc.). The properties defined in this section refer to the <border-style> value type, which may take one of the following values:

    none No border; the computed border width is zero. hidden Same as ‘none’, except in terms of border conflict resolution for table elements. dotted The border is a series of dots. dashed The border is a series of short line segments. solid The border is a single line segment. double The border is two solid lines. The sum of the two lines and the space between them equals the value of ‘border-width’ . groove The border looks as though it were carved into the canvas. ridge The opposite of ‘groove’: the border looks as though it were coming out of the canvas. inset The border makes the box look as though it were embedded in the canvas. outset The opposite of ‘inset’: the border makes the box look as though it were coming out of the canvas.

    All borders are drawn on top of the box’s background. The color of borders drawn for values of ‘groove’, ‘ridge’, ‘inset’, and ‘outset’ depends on the element’s border color properties, but UAs may choose their own algorithm to calculate the actual colors used. For instance, if the ‘border-color’ has the value ‘silver’, then a UA could use a gradient of colors from white to dark gray to indicate a sloping border.

    The ‘border-style’ property sets the style of the four borders. It can have from one to four component values, and the values are set on the different sides as for ‘border-width’ above.

    In the above example, the horizontal borders will be ‘solid’ and the vertical borders will be ‘dotted’.

    Since the initial value of the border styles is ‘none’, no borders will be visible unless the border style is set.

    8.5.4 Border shorthand properties: ‘border-top’ , ‘border-right’ , ‘border-bottom’ , ‘border-left’ , and ‘border’

    This is a shorthand property for setting the width, style, and color of the top, right, bottom, and left border of a box.

    The above rule will set the width, style, and color of the border below the H1 element. Omitted values are set to their initial values. Since the following rule does not specify a border color, the border will have the color specified by the ‘color’ property:

    The ‘border’ property is a shorthand property for setting the same width, color, and style for all four borders of a box. Unlike the shorthand ‘margin’ and ‘padding’ properties, the ‘border’ property cannot set different values on the four borders. To do so, one or more of the other border properties must be used.

    For example, the first rule below is equivalent to the set of four rules shown after it:

    Since, to some extent, the properties have overlapping functionality, the order in which the rules are specified is important.

    Consider this example:

    In the above example, the color of the left border is black, while the other borders are red. This is due to ‘border-left’ setting the width, style, and color. Since the color value is not given by the ‘border-left’ property, it will be taken from the ‘color’ property. The fact that the ‘color’ property is set after the ‘border-left’ property is not relevant.

    8.6 The box model for inline elements in bidirectional context

    For each line box, UAs must take the inline boxes generated for each element and render the margins, borders and padding in visual order (not logical order).

    When the element’s ‘direction’ property is ‘ltr’, the left-most generated box of the first line box in which the element appears has the left margin, left border and left padding, and the right-most generated box of the last line box in which the element appears has the right padding, right border and right margin.

    When the element’s ‘direction’ property is ‘rtl’, the right-most generated box of the first line box in which the element appears has the right padding, right border and right margin, and the left-most generated box of the last line box in which the element appears has the left margin, left border and left padding.

    Читать:
    Как передать массив в функцию python

Похожие статьи