How to set up smartphones and PCs. Informational portal
  • home
  • Windows 10
  • Css padding margin difference. Margin or padding? Thoughts on what to use and where

Css padding margin difference. Margin or padding? Thoughts on what to use and where

Hello, dear readers of the blog site. Today I want to continue the topic of study and consider those style rules that allow you to set indents and borders for Html elements: border, margin and padding.

Before this, we managed to study fairly simple properties that controlled fonts (), text () and looked at the model

Yes, we also managed to consider the principles of use in detail (extending over several articles). Now it’s time to move on to the rules that form the basis for constructing documents (web pages), and we will start with the block model (the relationship of Html elements).

In general terms, I have already written about modern technology, but today we will get into pure specifics. If you would like to read previous publications on the topic, you are welcome to .

Box model in CSS - padding, margin and border

Third, interest may be used. What are they counted from? It turns out that from container width(that is, from the content area of ​​the parent element). Moreover, this applies not only to margin-right and left, which would be logical, but also for margin-top and bottom, the percentages will be calculated precisely from the width (and not the height) of the container.

It should be noted, speaking about setting dimensional values, that Margin may also be negative. Those. when specifying a positive value for the outer margin, we move the adjacent element to the specified distance, and if we specify a negative value, the neighboring block will simply overlap the one for which we set this negative indentation. And this is used very often in CSS.

Well, it goes without saying that there is a prefabricated CSS Margin rule, which in many cases allows you to reduce the size of the code used to set the required external margins. The order of the values ​​in it is strictly regulated (they are written through a space character) and must correspond to the example:

Those. the enumeration starts from the top and continues clockwise until the circle is completed with the right indentation (right). It might look something like this:

Margin:20px 10px 40px 30px;

And this will mean that the browser above our block should indent 20 pixels, on the right - 10, below - 40, and on the left - 30. That is. this entry would be equivalent to:

The reduction of CSS code is visible to the naked eye. But this is not the limit. It is quite acceptable to use not only four, but also three, two, and even just one value in a prefabricated rule. Which will further help reduce the code size. However, it will be possible to reduce the number of values ​​only in certain cases:

  1. If the margins on the left and right are the same, for example, like this: margin:20px 30px 40px 30px;

    That last one can be omitted:

    Margin:20px 30px 40px;

    These two prefab rule entries do the same thing. Therefore, if you see an entry with three values ​​in Margin, then the value of the fourth (on the right) can be seen in the second (on the left).

    If the indentations above and below are equal, such a trick will no longer work, because logically it is possible to reduce the structure of the entry of a prefabricated rule, only cutting off duplicate values ​​from its end(and the value of the bottom indent will be second to last).

  2. If, in addition to equality of external margins on the left and right, there is equality of their values ​​at the top and bottom: margin:20px 30px 20px 30px;

    or, which is the same (due to point 1):

    Margin:20px 30px 20px;

    Then such a prefabricated rule can be written with only two values, discarding the last one, which coincides with the first:

    Margin:20px 30px; In this case, the first value describes the external margins vertically, and the second - horizontally.

  3. And finally, if all the values ​​in the prefab rule are the same: margin:20px 20px 20px 20px;

    or, which is the same (due to point 2):

    Margin:20px 20px;

    That can be used maximally abbreviated record type(discarding the last value that matches the first):

    Margin:20px; Which will mean the same margin on all sides of our Html element.

Speaking about external margins, it is worth mentioning such a scheme as "Margin-colloapse" or, in other words, “margin collapse.” In a nutshell, the essence of this phenomenon is as follows.

If we have two blocks located under each other (collapsing of margins can only occur vertically) and both of them are given opposite margins (for example, bottom for the top element and top margin for the bottom), then the larger Margin value will absorb the smaller one.

For example, if the top block is set to:

Margin:20px 20px 200px 20px;

And for the lower one:

Margin:100px 20px 20px 20px;

Then the lower margin of the upper block (200px) will absorb the upper margin of the lower one (100px, and even if it becomes equal to 199px, nothing will change) and the resulting external margin between these two blocks will still be equal to 200px. Those. only the larger one is taken into account modulo Margin, and it does not add up in any way with the counter value of the vertically adjacent element.

This is a catch that works exclusively vertically, and horizontally, opposing Margin dimensions will simply be added to each other. But this only applies to margins with the same sign, but if they are with different signs, then their numbers will simply add up and the blocks will be separated from each other by the resulting value.

For example, in this case:

Top margin:20px 20px -20px 20px; Bottom margin:10px 20px 20px 20px;

The resulting margin between blocks will be -10px, i.e. the bottom one will overlap the top Html element by 10px.

Another feature of using the Margin rule in CSS is that the specified value vertical for inline elements is ignored. By asking:

Margin:20px;

For example, for , which is an inline element, we will actually only see horizontal padding, and no changes will occur vertically.

Looking ahead a little, I’ll say that Padding vertically for inline tags will work, but the increased internal padding will not in any way affect its overall position relative to other neighboring elements.

In the case of a block tag (headings, paragraphs), increasing vertical Padding would move this element relative to other adjacent blocks.

Well, the frame (Border), or rather its width, will also not be able to move other adjacent blocks vertically away from the line tag. For inline elements, movement is only possible in one direction - horizontally and that’s it.

Padding and border - internal padding and frames

Let's now move on to setting padding using the Padding rule and see exactly what values ​​it can take:

As you can see, there is no mention of Auto here, and this CSS rule does not allow the use of negative values ​​(they can only be positive - from zero and above). Those. There is no way to push content beyond the frame using Padding. The maximum that can be done is to bring the content very close to the frame.

The percentages in it are calculated in the same way as in Margin - relative to the width of the container (the content area of ​​​​the parent element) in which our element is enclosed. Composite Padding Rule in Css is formed and obeys the same laws as discussed just above:

Padding:20px 10px 40px 30px;

In this rule, starting from the top, we describe all four sides. If you need to reduce something in it (to three, two or even one value), then you will need to use the reduction principles described just above for external indents, which will work with exactly the same success for internal ones.

And the last thing today I would like to consider is the framework that is set using Border. They have three types of parameters:

  1. Border-width — sets the thickness of the border
  2. Border-color — sets its color
  3. Border-style - the type of frame or the type of line with which it will be drawn

All three of these CSS rules have a valid set of values:

Line width for frame ( Border-width) can be specified either using numbers in Em, Ex or Px, or in words:

  1. Thin - thin line;
  2. Medium - average (this value is used by default);
  3. Thick - thick.
border-width:2px;

As a value for the border color ( Border-color) you can use the accepted methods for specifying them (hexadecimal code, words, etc.):

Border-color:red;

By default, if the border color is not explicitly specified, the one used for the font inside the element will be used.
The Border-style CSS property allows you to specify the border type in words:

  1. None - no frame (default)
  2. Dotted - the line is drawn in dots
  3. Dashed - dotted line
  4. Solid - solid line
  5. Double - double line
  6. Groove - depressed frame
  7. Ridge - protruding
  8. Inset and outset - shadow games

Naturally, since there are four sides to any block, you can use both general rules and separate ones for each side:

The same will apply to prefabricated Border rules— it can be specified both for all sides simultaneously (Border), and for each side separately (Border-top, left, bottom and right). The order of the values ​​is not important:

Border:1px solid red;

If you miss something, the default value will be used instead.

Good luck to you! See you soon on the pages of the blog site

You might be interested

Height, width and overflow - CSS rules for describing the content area in block layout
Position (absolute, relative and fixed) - ways to position Html elements in CSS (rules left, right, top and bottom) Different styling for internal and external links via CSS
Float and clear in CSS - block layout tools
Display (block, none, inline) in CSS - set the display type of Html elements on the web page
List style (type, image, position) - Css rules for customizing the appearance of lists in Html code
Background in CSS (color, position, image, repeat, attachment) - everything for setting the background color or background image of Html elements
What is CSS for, how to connect cascading style sheets to an Html document and the basic syntax of this language How to configure the alternating background color of rows of tables, lists and other Html elements on the site using the nth-child pseudo-class
Font (Weight, Family, Size, Style) and Line Height rules for styling fonts in CSS

The CSS padding property is responsible for setting the padding inside an element from its border

CSS padding syntax

padding: top right bottom left;
  • top - indent from the top border of the element;
  • right - indent from the right border of the element;
  • bottom - indent from the bottom border of the element;
  • left - indent from the left border of the element;

Values ​​are most often specified in pixels. You can also specify percentages and other valid CSS units.

Note 1
You can specify more than four values. Depending on the number of values, the actions will be different:

  • If 3 values ​​are specified, then the first value sets the indentation at the top, the second - at the same time on the left and right, and the third - at the bottom
  • If 2 values ​​are specified, then the first value sets the padding above and below, the second - to the left and right of the content
  • If the value is set to 1, then the indentation is set to the same indentation for all sides. For example:
padding: 10px 10px 10px 10px; You can specify it more compactly: padding: 10px;

Note 2
Unlike the CSS margin property, negative padding values ​​are not allowed.

Padding also has 4 separate CSS properties. Each of them is responsible for some direction.

  • padding-left - padding from the left border of the element;
  • padding-right - padding from the right border of the element;
  • padding-top - padding from the top border of the element;
  • padding-bottom - padding from the left border of the element;

For example

padding: 3px 5px 7px 10px; Or you can ask in detail: padding-left : 10px ; padding-right : 5px ; padding-top: 3px; padding-bottom : 7px ;

Examples with different indents inside an element

Example 1: Indent text within a tag

Пример с нулевыми отступам (padding: 0px)
Пример с одинаковым отступом от всех границ (padding: 10px)
Пример с разными отступам (padding: 10px 0px 0px 30px)

Вот как это выглядит на странице:

Пример с нулевыми отступам (padding: 0px)

Пример с одинаковым отступом от всех границ (padding: 10px)

Пример с разными отступам (padding: 10px 0px 0px 30px)

Пример 2. Отступ объекта внутри объекта

Описание

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

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

Синтаксис

padding: [значение | проценты] {1, 4} | inherit

Значения

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

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

HTML5 CSS2.1 IE Cr Op Sa Fx

padding

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

The result of this example is shown in Fig. 2.

Rice. 2. Applying the padding property

Object model

document.getElementById("elementID ").style.padding

Browsers

Internet Explorer versions up to and including 7.0 do not support the inherit value.

This property can have from one to four values.

In the image, the area for which the padding property is responsible is indicated in light gray:

  1. When specified four values(5px 10px 15px 20px) - the order of the internal padding will be as follows: Top(5px ) - Right(10px ) - Bottom(15px ) - Left(20px). To remember the order of indentation in one ad, you can use the English word TR ou B.L. e(where T- top, R- right, B- bottom, L- left).

  2. When specified three meanings(5px 10px 15px ) - the order of the internal padding will be as follows: Top(5px ) - Right & Left(10px ) - Bottom(15px).

  3. When specified two meanings(5px 10px ) - the first value (5px ) will set the size of the padding from the top and bottom of the element’s content, the second (10px ) value will set the padding to the left and right of the element’s content.

  4. When specified same value(5px) - the inner margin on all sides will be the same size - 5px.

Browser support

Property
Opera

IExplorer

Edge
padding1.0 1.0 3.5 1.0 4.0 12.0

CSS syntax:

padding: "length | initial | inherit" ;

JavaScript syntax:

Object.style.padding = "5px"

Property values

CSS version

CSS1

Inherited

No.

Animable

Yes.

Usage example

Element padding.
class = "primer" >
Eat some more of these soft French rolls and drink some tea.
Eat some more of these soft French rolls and drink some tea.
Eat some more of these soft French rolls and drink some tea.

Sets the value of the margins around the element's content. The margin is the distance from the inner edge of the element’s frame to the imaginary rectangle that bounds its contents (Fig. 1).

Rice. 1. Margin to the left of the text

The padding property allows you to set the margin value for all sides of an element at once or define margins only for specified sides.

brief information

Syntax

padding: [<размер> | <проценты>] {1, 4}

Designations

DescriptionExample
<тип> Indicates the type of the value.<размер>
A && BThe values ​​must be output in the order specified.<размер> && <цвет>
A | BIndicates that you need to select only one value from the proposed ones (A or B).normal | small-caps
A || BEach value can be used independently or together with others in any order.width || count
Groups values.[ crop || cross ]
* Repeat zero or more times.[,<время>]*
+ Repeat one or more times.<число>+
? The specified type, word, or group is optional.inset?
(A, B)Repeat at least A, but no more than B times.<радиус>{1,4}
# Repeat one or more times separated by commas.<время>#

Values

You can use one, two, three or four values, separated by a space. The effect depends on the number of values ​​and is shown in table. 1.

The size of the fields can be specified in pixels (px), percentages (%) or other units acceptable for CSS. When specifying the margin as a percentage, the value is calculated from the width of the element's parent.

Sandbox

Winnie the Pooh was always not averse to a little refreshment, especially at eleven in the morning, because at that time breakfast had long ended, and lunch had not yet begun. And, of course, he was terribly happy to see that the Rabbit was taking out cups and plates.

div ( background: #e4efc7; padding: (( playgroundValue ))px ; )

Example

padding

Conductometry gently conveys the electronic method of obtaining, regardless of the consequences of the penetration of methyl carbiol inside.

The result of this example is shown in Fig. 2.

Rice. 2. Applying the padding property

Object model

An object.style.padding

Specification

Each specification goes through several stages of approval.

  • Recommendation - The specification has been approved by the W3C and is recommended as a standard.
  • Candidate Recommendation ( Possible recommendation) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
  • Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
  • Working Draft - A more mature version of a draft that has been discussed and amended for community review.
  • Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
  • Draft ( Draft specification) - the first draft version of the standard.

Browsers

Browsers

The following notations are used in the browser table.

Best articles on the topic