What is the difference between padding and margin. PADDING and MARGIN properties and how to use them

This tutorial will help you better understand CSS properties such as border, padding and margin. These properties greatly help developers position elements on the page according to the layout.

Let's create a div and give it the properties margin, padding and border.

Padding property

The CSS padding property specifies the distance between the border of an element and its content. You can define it like this:

  • padding-top: 10px;
  • padding-right: 10px;
  • padding-bottom: 10px;
  • padding-left: 10px;

This entry can be shortened:

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

Note: the padding value is added to the element's width and depends on the element's background.

In other words we have div element with class div-1:

Div.div-1( width:150px; padding: 25px;)

The browser will add left and right padding to the element's width. As a result, we will get an element with a width of 200px.

Border property

The CSS border property allows you to define the style and color of an element's border.

border-width

The border-width property is used to determine the width of the border. The width is specified in pixels or using one of the predefined values: thin, medium, or thick.

border-color

The border-color property is used to define the color of the border. Color can be set in the following ways:

  • name - the name of the color, for example, “red”
  • RGB - defines the RGB value, for example, "rgb(255,0,0)"
  • Hex - defines a hex value, for example, "#ff0000"
border-style
  • dotted : Specifies a dotted border
  • dashed : Defines a dashed border
  • solid : Defines a thick border
  • double : Defines two borders. The distance between them depends on the border-width value
  • groove : Defines a 3D indented boundary
  • ridge : Defines a 3D raised border
  • inset : Defines a border so that the block wobbles indented
  • outset : Defines a boundary so that the block rolls out convex

You can write the element's border properties in a shorthand way:

Div.div-2( border:1px solid #ccc; )

Margin property

The CSS margin property specifies the amount of space around an element. Margin clears the space around the element (outside the border). Margin has no background color and is always transparent.

You can define margin values ​​for an element like this:

  • margin-top:100px;
  • margin-bottom:100px;
  • margin-right:50px;
  • margin-left:50px;

This entry can be shortened:

  • margin:25px 50px 75px 100px;
    • top margin 25px
    • right margin 50px
    • bottom margin 75px
    • left margin 100px
  • margin:25px 50px 75px;
    • top margin 25px
    • right and left margin 50px
    • bottom margin 75px
  • margin:25px 50px;
    • top and bottom margin 25px
    • right and left margin 50px
  • margin:25px;
    • all four margin 25px

Using the default margin values ​​you can center the block horizontally.

Source: Margin or padding?
Philip Sporrer.
Translation: vl49.

When is it better to use margins and when to use padding for formatting purposes, and does it make any difference?

I struggled for a very long time in search of suitable answers. It was only after writing a lot of terrible, indecipherable CSS code, accompanied by various side effects, that I could confidently say that I had found the fundamental ironclad rules regarding the issues listed above.

For clarity, let's turn to typical situation, which is most likely familiar to every developer user interface in 2017. We have a simple card template.

IN in this example There are two types of intervals:

  • between cards (blue);
  • between the cards and their container (green);
  • It is very important to understand here that we are dealing with two different concepts that should not be interrelated when assembled. That is, if I need to change the distance between the cards and their container, for example, to 24 pixels, then this should not in any way affect the spacing between the cards themselves.

    Implementing the example using CSS?

    There are literally thousands of ways to create a template like this using margins and padding, but I'd like to present one that demonstrates the correct use of the margin and padding properties. Moreover, this method allows you to add other cards in the future.

    Container (
    padding: 16px;
    }
    .card + .card (
    margin: 0 0 0 8px;
    }

    Just 2 selectors and 2 rules.

    What function does the plus sign perform?

    The + symbol represents an adjacent selector. It points only to the element that immediately follows the element specified before this selector.

    As can be seen from the image above, in our case, this selector will select every card that is preceded by any other card. So, using the adjacent selector, we can set the left margin for each card except the first one.

    This means that we have the opportunity to add any required amount cards, the distance between which will always be eight pixels.

    Everything works fine until we need to place something other than a card next to the cards. Well, let's say a button "Add card" ("Add card"):

    Judging by the existing CSS code snippet, we most likely would not assign the class .card to the new element representing the button, since it is not a card. How to be? Is it worth creating an additional class name .add-card for this, which contains the same rule with the margin property as the .card class? No, there is a better solution.

    Lobotomized owl *+* .

    What does it look like? Despite the funny association, this method works great and I have been using it constantly since I learned of its existence. So what's this all about? Here's a look at the corresponding CSS code:

    Container (
    padding: 16px;
    }
    /* well, did you recognize the lobotomized owl? 😜 */
    .container > * + * (
    margin: 0 0 0 8px;
    }

    As you may remember, the previous selector applied to any card that was preceded by another card. Now with its help we can format every element immediately before which is any other element, including the button, of course.

    Eventually.

    I sincerely hope that the material presented here has helped you understand when to use padding and when to use margins to separate content within a container.

    As a result, I would like to present for your consideration a pen-project demonstrating the above examples, as well as those tested on own experience two rules. So, let's use:

    padding - for spaces between the container and its content.

    margin - for spaces between elements inside the container.

    • 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

    11/21/16 2K

    Today we will work on understanding the difference between HTML padding (inline padding) and margin ( margin) in CSS. But first, let's understand their syntax. There are several ways to write these properties: regular and shorthand:

    Padding and Margin in CSS

    The normal form of notation for the properties in question is easier to understand because it is similar to all other style notations:

    Regular entry:

    padding-top: 10px; padding-right: 20px; padding-bottom: 10px; padding-left: 20px;

    The CSS shorthand, on the other hand, combines all of these properties into one common "padding" property.

    Brief entry:

    padding: 10px 20px 40px 10px;

    Padding and margin have four values: top, right, bottom, and left. The shorthand notation shown above also specifies four values, separated by a space. The first of four values ​​is padding at the top, then padding at the right, bottom (padding bottom HTML) and at the left:

    padding: TOP RIGHT BOTTOM LEFT; (padding: top right bottom left)

    This entry can be reduced to three values ​​if the left and right padding/margin are the same. For example, if the top margin is 30px, the left and right are 10px, and the bottom is 40px, then you can use the following notation:

    padding: 30px 10px 40px;

    We reduce it to two values!

    If the top and bottom padding/margin are the same, and the right and left padding/margin are also the same, then only two values ​​can be specified. In this example, we have a top and bottom padding of 10px, and a left and right padding of 20px. Our CSS will look like this:

    padding: TOP/BOTTOM RIGHT/LEFT; (padding: top/bottom right/left) padding: 10px 20px;

    Only one meaning!

    Our latest version shorthand for padding and margin HTML contains only one value. This notation can be used when all indents (top, bottom, right and left) have the same value. If we wanted all sides to have 20px padding, the CSS would look like this:

    When to use which recording format? For example, if I want to give an element only a bottom padding, I'll use the regular notation since I only need to apply the property to one side: padding-bottom: 30px ;

    How to work with PADDING and MARGIN

    There is a noticeable difference between these two properties. Padding is used to define space within an HTML element's container. Margin is used to define the space around the outer border of elements.

    Imagine padding putting a winter coat on you. The coat is part of you, but if I threw paint at you, it would cover a wider area than if you weren't wearing that coat.

    You can also think of padding as filler in cardboard box. When you fill a box with foam, you use it to hold the contents away from the edges of the box. Padding in CSS does the same thing.

    Now think of margin as an invisible force field around you. The force field keeps other things away from you. Going back to the coat and paint example, if I were to throw paint at you and it was able to pass through the force field, then it would still only cover you and your coat.

    PADDING and MARGIN on the example of a site

    Let's look at properties using examples with elements. We'll start with a paragraph (tag

    ), then add a background color to it and add 30px padding on each side.

    Below on the left you can see that it is a paragraph with 30px padding around it. In the image on the right I used the tools Google Chrome to show where the HTML padding starts/ends for this element. Green color in the image below is the padding that is placed around the container. The dark blue background color fills the inner area:

    Now let's add a margin to the paragraph. I'll add 30px top and bottom padding, as well as 20px left and right. The image below on the left shows how this paragraph has changed from margin . The actual width of the image has become smaller because the margin pushes away from the borders of the other HTML element. On the right you can see that Orange color– this is the margin around the element. margin is always outside the padding and the dark blue background does not extend into the margin area.

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

    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's boundaries, 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 usually 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 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 move 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 that cannot contain child elements, such as the 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 field properties set the size of the space outside the border field. 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.