Padding html что это
Перейти к содержимому

Padding html что это

  • автор:

Padding html что это

Contents

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.2. auto See the section on calculating widths and margins for behavior.

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.
  • If the top margin of a box with non-zero computed ‘min-height’ and ‘auto’ computed ‘height’ collapses with the bottom margin of its last in-flow child, then the child’s bottom margin does not collapse with the parent’s bottom margin.

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’ collapses with its last in-flow block-level child’s bottom margin, if:
      • the box has no bottom padding, and
      • the box has no bottom border, and
      • the child’s bottom margin neither collapses with a top margin that has clearance, nor (if the box’s min-height is non-zero) with the box’s top margin.

      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.2.

      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:

      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’ 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.

      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.

      padding¶

      Свойство padding устанавливает значение полей вокруг содержимого элемента.

      Полем называется расстояние от внутреннего края рамки элемента до воображаемого прямоугольника, ограничивающего его содержимое (рис. 1).

      Рис. 1. Поле слева от текста

      Свойство padding позволяет задать величину поля сразу для всех сторон элемента или определить поля только для указанных сторон.

      • padding

      Синтаксис¶

      Значения¶

      Разрешается использовать одно, два, три или четыре значения, разделяя их между собой пробелом. Эффект зависит от количества значений и приведен в табл. 1.

      Табл. 1. Зависимость от числа значений

      Число значений Результат
      1 Поля будут установлены одновременно от каждого края элемента.
      2 Первое значение устанавливает поля от верхнего и нижнего края, второе — от левого и правого.
      3 Первое значение задает поле от верхнего края, второе — одновременно от левого и правого края, а третье — от нижнего края.
      4 Поочередно устанавливается поля от верхнего, правого, нижнего и левого края.

      Величину полей можно указывать в пикселях (px), процентах (%) или других допустимых для CSS единицах. При указании поля в процентах, значение считается от ширины родителя элемента.

      padding

      Свойство padding — или внутренний отступ — позволяет оттолкнуть контент от границ родительского элемента.

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

      Можно управлять отступами по отдельности при помощи свойств padding — top , padding — left , padding — right , padding — bottom .

      Пример

      Скопировать ссылку на секцию «Пример» Скопировано

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

      Попробуем добавить внутренний отступ — padding .

      Почему в данном случае не следует задавать margin или padding для элемента с классом .content чтобы оттолкнуть его от краёв родителя? Потому что нужно стараться верстать максимально гибко с расчётом на изменения в дальнейшем.

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

      А если задать отступ для элемента .content , а завтра его заменят на .content — 2 , то отступ пропадёт, и вёрстка потеряет свой исходный вид.

      Как понять

      Скопировать ссылку на секцию «Как понять» Скопировано

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

      Как пишется

      Скопировать ссылку на секцию «Как пишется» Скопировано

      Пишем свойство padding и через двоеточие после пробела указываем значение.

      Значения можно указывать в любых относительных или абсолютных единицах измерения, доступных в вебе: px , em , rem , % , vh , vw и так далее. Также можно использовать функцию calc ( ) .

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

      • padding : 10px 15px 20px 30px — читается по часовой стрелке начиная с верхней границы. Сверху 10 пикселей —> справа 15 пикселей —> снизу 20 пикселей —> слева 30 пикселей. Все вычисления в вебе начинаются от верхнего левого угла. Запомни этот порядок. Он часто нужен при чтении кода.
      • padding : 15px — со всех четырёх сторон будет одинаковый отступ в 15 пикселей.
      • padding : 15px 20px — парные противоположные отступы. Первое значение для верхнего и нижнего отступов: сверху и снизу по 15 пикселей. Второе значение для боковых отступов: справа и слева по 20 пикселей.
      • padding : 10px 5px 25px — первое значение для верхнего отступ (сверху 10 пикселей), второе значение для боковых отступов (справа и слева по 5 пикселей), последнее значение для нижнего отступа (снизу 25 пикселей).

      Подсказки

      Скопировать ссылку на секцию «Подсказки» Скопировано

      �� Свойство не наследуется.

      �� Значение по умолчанию — 0 .

      �� Внутренний отступ не может быть отрицательным.

      �� Отступы можно анимировать при помощи свойства transition ��

      �� У вертикальных отступов нет проблемы схлопывания как у margin .

      �� У списков есть левый отступ по умолчанию. Не забывай его сбрасывать, если используешь списки только для группировки объектов.

      Левый отступ по умолчанию у списков

      �� В инструментах разработчика в Chrome padding подсвечивается зелёным цветов. В Firefox при инспектировании элемента внутренний отступ обозначается светло-сиреневым цветом.

      На практике

      Скопировать ссылку на секцию «На практике» Скопировано

      Егор Левченко советует

      Скопировать ссылку на секцию «Егор Левченко советует» Скопировано

      �� Чтобы понять padding представьте лист бумаги с напечатанным на принтере текстом. Видите эти отступы по краям листа? Они внутри и это тот самый padding ! padding стоит использовать, чтобы указать отступы от краёв блока и навсегда отказаться от margin — top . Правильно задав границы, вы сможете упорядочить все прочие отступы у элементов внутри вашего блока.

      Алёна Батицкая советует

      Скопировать ссылку на секцию «Алёна Батицкая советует» Скопировано

      �� Самая прикольная фишка, которую можно реализовать при помощи padding — адаптивные картинки, которые при изменении ширины экрана изменяют свой размер, но не деформируются.

      �� Попробуй менять размеры окна браузера и понаблюдать за поведением обоих блоков. Первый будет всегда сохранять пропорции 16:9, а вот второй всегда будет высотой 200 пикселей.

      Таблица значений padding-bottom для разных стандартных соотношений сторон:

      CSS Padding

      Padding is used to create space around an element’s content, inside of any defined borders.

      CSS Padding

      The CSS padding properties are used to generate space around an element’s content, inside of any defined borders.

      With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).

      Padding — Individual Sides

      CSS has properties for specifying the padding for each side of an element:

      • padding-top
      • padding-right
      • padding-bottom
      • padding-left

      All the padding properties can have the following values:

      • length — specifies a padding in px, pt, cm, etc.
      • % — specifies a padding in % of the width of the containing element
      • inherit — specifies that the padding should be inherited from the parent element

      Note: Negative values are not allowed.

      Example

      Set different padding for all four sides of a <div> element:

      Padding — Shorthand Property

      To shorten the code, it is possible to specify all the padding properties in one property.

      The padding property is a shorthand property for the following individual padding properties:

      • padding-top
      • padding-right
      • padding-bottom
      • padding-left

      So, here is how it works:

      If the padding property has four values:

      • padding: 25px 50px 75px 100px;
        • top padding is 25px
        • right padding is 50px
        • bottom padding is 75px
        • left padding is 100px

        Example

        Use the padding shorthand property with four values:

        If the padding property has three values:

        • padding: 25px 50px 75px;
          • top padding is 25px
          • right and left paddings are 50px
          • bottom padding is 75px

          Example

          Use the padding shorthand property with three values:

          If the padding property has two values:

          • padding: 25px 50px;
            • top and bottom paddings are 25px
            • right and left paddings are 50px

            Example

            Use the padding shorthand property with two values:

            If the padding property has one value:

            • padding: 25px;
              • all four paddings are 25px

              Example

              Use the padding shorthand property with one value:

              Padding and Element Width

              The CSS width property specifies the width of the element’s content area. The content area is the portion inside the padding, border, and margin of an element (the box model).

              So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.

              Example

              Here, the <div> element is given a width of 300px. However, the actual width of the <div> element will be 350px (300px + 25px of left padding + 25px of right padding):

              To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.

              Example

              Use the box-sizing property to keep the width at 300px, no matter the amount of padding:

              More Examples

              Set the left padding
              This example demonstrates how to set the left padding of a <p> element.

              Set the right padding
              This example demonstrates how to set the right padding of a <p> element.

              Set the top padding
              This example demonstrates how to set the top padding of a <p> element.

              Set the bottom padding
              This example demonstrates how to set the bottom padding of a <p> element.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *