What is padding and margin. When to use margin vs padding in CSS. Box model in CSS - padding, margin and border

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 quite a lot simple properties which manipulated 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 outline I’ve already written about modern ones, but today we’ll get into pure specifics. If you would like to take a look previous publications on the topic, then 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 the width of the container (that is, the content area 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 can 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 space character) and should match the example:

Those. the enumeration starts from the top and continues clockwise until the circle ends with the right indentation. 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:

  • 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 indents above and below are equal, such a trick will no longer work, because logically it is possible to reduce the structure of a prefabricated rule record only by cutting off the duplicate values ​​from its end (and the value of the lower indent will be the penultimate one).

  • 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, what 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.

  • 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;

    Then it will be possible to use the most abbreviated record type (discarding last value coinciding with 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, “collapsing margins”. 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 opposite margins are set for both of them (for example, bottom for the top element and top margin for the bottom), then higher value Margin will absorb less.

    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 modulo Margin is taken into account, 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 vertical value for inline elements 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 line tags will work, but the increased internal padding will not affect it in any way general situation 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. The Padding rule in Css is formed and obeys the same laws as discussed 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 with using Border. They have three types of parameters:

  • Border-width — sets the thickness of the border
  • Border-color — sets its color
  • 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:

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

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

    As a value for the border color (Border-color), you can use the accepted methods for setting 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.
    CSS Border-style property allows you to specify the frame type in words:

  • None - no frame (default)
  • Dotted - the line is drawn in dots
  • Dashed - dotted line
  • Solid - solid line
  • Double - double line
  • Groove - depressed frame
  • Ridge - protruding
  • Inset and outset - shadow games
  • Naturally, since there are four sides of any block, it can be used as general rules, and separate for each side:

    The same will apply to the combined Border rule - it can be written 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! Before see you soon on the pages of the blog site

    You can watch more videos by going to ");">

    You might be interested

    Height, width and overflow - CSS rules to describe a content area in block layout
    Position (absolute, relative and fixed) - methods Html positioning elements in CSS (rules left, right, top and bottom) Different design for internal and external links via CSS
    Float and clear in CSS - tools block layout
    Display (block, none, inline) in CSS - set the type HTML display elements on a web page

    In the previous chapter, we mentioned CSS properties such as margin and padding. Now we will look at them in more detail and consider how they differ from each other and what features they have.

    You can create spaces between elements in one or another way, but if padding is the indentation from the content to the edge of the block, then margin is the distance from one block to another, the interblock space. The screenshot shows a clear example:

    Padding separates content from the block border, and margin creates gaps between blocks

    As you can see, the fields and CSS padding differ from each other, although sometimes without looking at the code it is impossible to determine which property is used to set the distance. This happens in cases where the frame or background of the content block is missing.

    The following properties exist to set margin or padding in CSS on each side of an element:

    Padding:

    • padding-top: meaning;
    • padding-right: meaning;
    • padding-bottom: meaning;
    • padding-left: meaning;

    Fields:

    • margin-top: meaning;
    • margin-right: meaning;
    • margin-bottom: meaning;
    • margin-left: meaning;

    Values ​​can be specified in any CSS units– px, em, %, etc. Example: margin-top: 15px .

    There is also very convenient thing as shorthand for margin and padding CSS. If you need to set margins or padding on all four sides of an element, you don't have to write the property for each side individually. Everything is made simpler: for margin and padding you can specify 1, 2, 3 or 4 values ​​at once. The number of values ​​determines how the settings are distributed:

    • 4 values: padding is set for all sides of the element in the following sequence: top, right, bottom, left: padding: 2px 4px 5px 10px;
    • 3 values: the padding is set first for the top side, then simultaneously for the left and right, and then for the bottom: padding: 3px 6px 9px;
    • 2 values: padding is set first simultaneously from the top and bottom sides, and then simultaneously for the left and right: padding: 6px 12px;
    • 1 value: equal padding is set for all sides of the element: padding: 3px;

    The same rules apply to margin properties CSS. Please note that you can also use negative values ​​for margin (for example -3px), which can sometimes be quite useful.

    Collapse margin

    Imagine the situation: two block element are located on top of each other and are given margin fields. The top block is set to margin: 60px , and the bottom block is set to margin: 30px . It would be logical to assume that the two bordering fields of two elements will simply touch and, as a result, the gap between the blocks will be equal to 90 pixels.

    However, things are different. In fact, in such a situation, an effect occurs that is called collapse, when the largest in size is selected from two adjacent fields of elements. In our example, the final gap between elements will be 60 pixels.


    The distance between blocks is equal to the larger of the values

    Collapsing margin only works for the top and bottom margins of elements and does not apply to the margins on the right and left sides. The final gap value is calculated in different situations differently:

    • When both margin values ​​are positive, the resulting margin size will be equal to the larger value.
    • If one of the values ​​is negative, then to calculate the field size you need to get the sum of the values. For example, with values ​​of 20px and -18px the field size will be equal to:
      20 + (-18) = 20 – 18 = 2 pixels.
    • If both values ​​are negative, the moduli of these numbers are compared and the number with the larger modulus (hence the smaller of the two) is selected. negative numbers). Example: you need to compare the values ​​of the -6px and -8px fields. The moduli of the numbers being compared are 6 and 8, respectively. It follows that 6 -8. The resulting field size is -8 pixels.
    • In the case where the values ​​are specified in different units CSS, they are reduced to one, after which they are compared and the larger value is selected.
    • margin size for child elements it is defined even more interestingly: if the child has a larger margin field than the parent, then priority is given to it. In this case, the sizes of the top and bottom margins of the parent will be the same as those specified for the child. In this case, there will be no distance between parent and child.

    19 answers

    TL; DR: By default I use a margin everywhere except when I have a border or background and I want to increase the space inside that visible margin.

    For me the most a big difference between padding and margin is that vertical margins are automatically compressed, but padding is not.

    Consider two elements, one above the other, each with 1em indentation. This indentation is considered part of the element and is always retained.

    So you will get the content of the first element, followed by the padding of the first element, then the padding of the second, and then the content of the second element.

    So the content of these two elements will end up being 2em by 2 elements.

    Now replace this padding with a 1em margin. Margins are considered to be outside the element, and the margins of adjacent elements will overlap.

    So in this example you will get the content of the first element, followed by 1em of the combo box, and then the content of the second element. Thus, the content of these two elements is 1 1em apart.

    This can be very useful when you know you want to tell 1em space between elements, no matter what element it's next to.

    Two other big differences are that padding is included in the click area and background/image color, but not in the box.

    The best I've seen explaining it with examples, diagrams and even "try it for yourself" is this.

    The chart below gives the instantaneous visual representation about the difference.

    One thing to keep in mind is that standards-compliant browsers (IE quirks are the exception) only display a portion of the content at a given width, so keep track of this in your layout calculations. Also notice that there is Bootstrap 3 support visible in the window frame.

    MARGIN vs PADDING:

      Margin is used in an element to create distance between that element and other elements on the page. When padding is used to create distance between content and the border of an element.

      Margin is not part of the element, where padding is part of the element.

    There's more technical explanation for your question, but if you're looking for a way to think about margin and padding that will help you choose when and how to use them, this might help.

    Compare the elements of the block with the pictures hanging on the wall:

    • The browser window is like a wall.
    • the content is similar to photography.
    • margin is like the space between framed images.
    • the addition is like matting around the photo.
    • The border is similar to the frame border.

    When deciding on margin and padding, it's a good rule of thumb to use margin when you position an element in relation to other things on the wall and padding. > when you set up appearance the element itself. Margin will not change the size of the element, but padding will generally make the element larger than 1 .

    1 This default window model can be changed using the box-sizing attribute.

    As for margins, you don't have to worry about the width of the element.

    Just like when you give something (padding: 10px;), you need to reduce the element's width by 20px to keep the "fit" and not break other elements around it.

    So I usually start by using paddings to get everything "packed" and then use margins to make small adjustments.

    Another thing to be aware of is that paddings are more compatible in different browsers, and IE doesn't handle negative margins very well.

    Here's some HTML that demonstrates how padding and margin affect click-through rates and background fill. The object receives clicks on its padding, but clicks on the object's margin"d region to go to its parent object.

    $(".outer").click(function(e) ( console.log("outer"); e.stopPropagation(); )); $(".inner").click(function(e) ( console.log("inner"); e.stopPropagation(); )); .outer ( padding: 10px; background: red; ) .inner ( margin: 10px; padding: 10px; background: blue; border: solid white 1px; )

    Margins clear the area around the element (outside the border), but padding clears the area around the content (inside the border) of the element.

    this means that your element doesn't know about its outer bounds, so if you're designing dynamic web controls, I recommend using padding and margining if you can.

    Please note that several times you need to use margin.

    In CSS, there are two ways to create space around your elements: margins and padding. In most use cases they are functionally identical, but in truth they behave somewhat differently. There are important differences between margins and padding that you should consider when choosing what to use to move elements around the page. However, in cases where any margin or padding can be used for the same effect, many decisions come down to personal preference.

    When to use fields

      You want your spacing to appear outside the box created by the border property. Margins lie outside the borders, so you use them if you want your border to stay in one place. This may be useful if you have e.g. side panel with a border that you want to extend away from the main content area.

      You don't want the background color or image to invade your personal space. Background colors and the images stop at the border, so if you'd rather keep your backgrounds outside of the space you're making, margins are the property you want.

      You want to reset space at the top and bottom of your element. Top and bottom margins behave differently than side margins; if two margins are placed on top of each other, they collapse to the same size as the side margins. large set fields. For example, if I set a paragraph with a 20px top margin and a 15px bottom margin, I'll only have 20px of space between the paragraphs (the two margins fall apart on top of each other, and the biggest wins).

    When to use a gasket

      You want all the space you create to be within your boundary. The padding is inside your borders, so it's useful for pushing your borders away from the content inside your element.

      You want your background color/image to continue in the space you create. Your background will continue behind your addition, so only use it if you want the look of your background.

      You want your top and bottom to behave more rigidly. For example, if you set paragraphs in your document to have a top padding of 20px and a bottom padding of 15px, then any time you had two paragraphs per line, they actually have in total 35 pixels of space between them.

      Difference between extended field and explanation

      It is not practical to use padding on the content space in an element; you should use margin on the child element. Old browsers such as Internet Explorer, misinterpreted the window model except when using margin , which works fine in Internet Explorer 4.

      There are two exceptions to padding:

        It applies to an inline element, which cannot contain child elements such as an input element.

        You compensate greatly different error browser that the seller *cough* Mozilla *cough* refuses to fix and to be sure (to the extent that you regularly exchange with W3C and WHATWG editors) you should have working solution and this decision will not affect the styling of anything other than the error you are compensating for.

      When you have an element 100% width with padding: 50px; , you will get width: calc(100% + 100px); . Since margin is not added to width , it won't cause unexpected layout problems if you use margin on child elements instead of padding directly on the element.

      So, unless you do one of these two things, don't add padding to the element, but rather use a child/children element on it to ensure the expected behavior in all browsers.

      First let's see what the differences are and what each responsibility is:

      1) Margin

      CSS margin properties are used to create space around elements.
      The margin properties set the size of the space outside the border margin. With CSS you have complete control over the fields.
      There are CSS Properties to set the margin for each side of the element (top, right, bottom, and left).

      2) Gasket

      CSS firmware properties are used to create space around the content.
      The padding clears the area around the content (inside the border) of the element.
      With CSS you have full control over the addition. There are CSS properties to set padding for each side of the element (top, right, bottom, and left).

      So simply, Margin is the space around elements, and Padding is the space around the content that is part of the element.

      This image from codemancers shows how borders and boundaries become accessible, and how borders and the content box make them different.

      While wandering around the forums I came across the fact that the question still arises of what padding does and what margin does, and what are the differences between them. That is why I decided to remind you of this. So, without resorting to abstruse phrases Let’s pose the problem and look at an example in which everything will become clear.

      Task: on the page I need a red block(200x200 pixels), which recedes from the edges of the browser top and left by 40 and 70 pixels respectively, and the text inside of which is indented to the left and top by 40 pixels.

      Solution: look at the picture and the code. Our red block should not exceed 200 by 200 pixels and it should be indented from the edges of the browser (or other content blocks). Actually, we make these indents through margin. If we do padding, then the indentation occurs inside our red block and the indentation is obtained with the background of the block itself (that is, red).


      .block(
      width: 160px;
      height: 160px;
      background-color: red;
      margin-top: 40px;
      margin-left: 70px;
      padding-top: 40px;
      padding-left: 40px;
      }


      text, text, a lot of text, a lot of text text

      In addition to the properties used (lines 6-9), there are also properties margin-right, padding-right, margin-bottom, padding-bottom - they are for indentation on the right and bottom, respectively. The values ​​for all of these properties can be in pixels (px), percentages (%), or em units.

      In principle, that's all. However, there are still some features of working with them.

      Features of margin and padding

      When using padding, the dimensions of the padding must be subtracted from the height and width of the block, otherwise the size of the block will increase by the size of the padding.

      If a block is given margin-left and margin-right values ​​of auto, then if the block has a fixed width (for example, 400px) and does not have a float CSS property, then this block will be aligned to the center of the element in which it is located. Actually, for non-rubber layout with center alignment, this alignment method is usually used. Despite the fact that IE 5.5 and earlier do not support the auto value, this still does not prevent you from using it all the time =).

      It is not advisable to use padding and margin in tables because the effect will be unpredictable in different browsers.

      And the last thing I wanted to say. Don't forget to use shorthand notation constructs, such as margin: 10px 0 5px 20px;. If the indentation is zero, then you can simply put a zero, without specifying the parameters. It is very easy to remember which of the parameters relates to which boundary - for a block, the indents go clockwise: the first number is on top, the second is on the right, the third is on the bottom, the fourth is on the left.

      That's actually all I wanted to tell you today. Happy weekend everyone!

      October 18, 2017 at 03:36 pm Organization of indentation in layout (margin/padding)
      • CSS
      • HTML
      • Tutorial

      The purpose of this article is not to complicate simple things, but to focus attention on well-known standards that are somehow forgotten. It's important to maintain a meaningful structure in all aspects of your layout, and it's equally important to adhere to it in your indentation. And one of the main principles of layout is flexibility. Namely, the ability to easily make any changes without breaking anything. Proper handling with margin and padding plays a very big role in this matter.

      The following principles are implemented in the environment of positioning elements on the page. They are also used in decorative elements. But not so categorically.

      Basic principles:

    • The indentation is given to the last possible element in the house.
    • Indents cannot be set for independent elements (BEM block).
    • For the last element of the group, the indent is reset to zero (always).
    • Indents go from the previous element to the next. margin(s) are set from the previous element to the next, from the first to the second, from top to bottom, from left to right.

      This means that properties such as margin-left and margin-top are not used (with some exceptions). With padding, everything is a little opposite (except that it is used for decorative purposes, increasing the link area, etc.). When a block needs padding on the top or left, it gets it from the parent's padding-top and padding-left.

      The indentations go in the direction of the flow of the tree house, the block does not push itself.
      Initially, he is in a static position, and receives some kind of impact at the expense of others.

      The margin is set to the last possible element in the house. margin(s) are set only between adjacent elements of the tree house.

      In the example there are 3 lists, in the following structure:

      • Far, far away, beyond the verbal.
      ... ...

      The indentation is made not at the expense of child elements, but at the expense of neighboring ones.

      In this situation, .main-section__item is the last possible one that can be indented to separate the lists. The same effect can be achieved by indenting a div, a list, a line, or a link, but this will not be correct.

      This example is quite simple. But if you imagine a much larger nesting, where someone littered with indents, when some margins collapse. and some are added to paddings.

      headline in a section of seven words
      If we take the example of a title, and you need to indent the title at the top. then the last element will be section and padding-top is set for it, margin(s) which are by default always need to be reset.

      The most simple reason which is worth sticking to this principle, this is to make it easier to find the indentation in the future, either for you or for someone who will work with your layout in the future. This is about convenience.

      The real problems can arise when layout with poor indentation structure is rendered dynamically or duplicated.

      Indents cannot be set for independent elements (BEM block) Never indent elements that can be used more than once. Even if you don't follow methodologies, keep things in perspective. There are wrappers for this. Wrappers are good. Or additional classes.

      If you need to indent the block. Without prejudice, this is done using:

      • Inheritance through the element (if you pull this block from the element, there will be no indentation, and you can simply place it in another place).
      • Adding a class (you can make a block an element).
      • Wrapper (like a block that has a role, only in positioning).
      .block__item > .block ( margin-right: 10px; ) .block.block__item ( margin-right: 10px; ) .block-wrap > .block ( margin-right: 10px; ) For the last element of the group, the margin is reset to zero (always) Let's take a list and an image as an example.

      This horizontal menu and the logo (which for some reason is on the right).

      For the last li, the indentation is reset to zero. And the indentation is made between adjacent ul and img elements. What was discussed in the second principle.

      Let's take another example:

      ... 10.10.10 ... ...

      We are interested in the margin between the news that is set.blog-preview__item (margin-bottom: 20px;). The last margin is reset to zero, and the bottom indentation is made by padding blog-preview . What was discussed in the second principle.

      More often than other pseudo-classes, you should use:last-child.

      Item:not(:last-child) ( margin-bottom: 20px; ) // or // .item ( // other styles // margin-bottom: 20px; &:last-child ( margin-bottom: 0; ) ) // or margin-top, the main idea here is not in the direction of margin, but in the absence of excess // .item + .item ( margin-top: 20px; ) // or // .item ( // other styles // & + & ( margin-top: 20px; ) )

      Exceptions

      Of course there are special cases non-trivial tasks, and nuances in which it is impossible to adhere to these principles, but otherwise it is worth striving for ideal indentations in order to make the layout as clean as possible.

      P.S. I advise you to read the publication