When to use margin vs padding in CSS. 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 a 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 : Specifies 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 always remains 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.

  • 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 of margin and padding plays a very important 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 simplest reason why you should adhere to this principle 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 is a horizontal menu and 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

    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 biggest difference between padding and margin is that vertical margins automatically shrink while padding does 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 diagram below gives an instant visual idea of ​​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 Bootstrap 3 support is 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 customize the appearance of 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 across browsers, and IE doesn't treat 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 area 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 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.

    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 can be useful if you have, for example, a sidebar 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 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 fields are placed on top of each other, they collapse to the size of the largest set of 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 20 pixels and a bottom padding of 15 pixels, then any time you had two paragraphs per line, they actually have a total of 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. Older 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 are compensating for a very different browser bug that the vendor *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 a working solution and this solution will not influence 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 complete control over your content. 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.

      From the author: When I first started learning CSS, I kept getting confused about margin and padding. They seemed very similar, and in some cases gave the same result. In this tutorial, you'll see the difference between CSS margin and padding, and how these properties affect the space between elements on the page. We will also discuss collapsing margins and using different units of measurement when creating responsive websites. We'll end the article with a couple of tips on layout using margin and padding.

      Block model

      Elements in CSS are represented as rectangular boxes. The size of a rectangular block is determined by the properties of the element: content, padding, frame, margin.

      The element's content area is located in the middle. Next, padding surrounds the content area. The frame surrounds the padding, and the margin is the outer layer, i.e. it is outside the element. To better understand what we are talking about, below is a diagram.

      As you can see from the diagram, padding is a layer that extends an element from the outer edge of the content area to the inner edge of the frame. This property controls the distance between the element's border and its content. Padding affects the size of an element on a page, but it has no effect on the spacing between elements on a page.

      If you need to increase or decrease the distance between elements, use margin. The margin property does not affect the size of the element in any way.

      It is important to remember that the sizes of all blocks on a web page depend on the block model used. There are two block models: W3C block model, traditional block model.

      According to the W3C block model, the width of an element is calculated from the content of the block without taking into account padding and margin. Padding and border are added on top of the specified dimensions, which can have unpredictable effects on the page layout.

      For example, let's take a block with a width of 200px and a height of 200px, padding of 10px on all sides and a border of 2px on all sides. The browser does not see the 200px block. The browser calculates the horizontal space required to display the block, and it is 224px: 200(width)+2(left border)+10(left padding)+10(right padding)+2(right border)=224px. Since this is a square, the height will also be 224px.

      On the other hand, the traditional block model takes the sum of the content, padding and border as the width. This means that if your block is 200px wide, the browser will calculate the horizontal space needed to display it, and it will be 200px, including padding and border. The result is more predictable and easier to work with.

      By default, all browsers use the W3C block model. The model can be set manually using the box-sizing property. Two values ​​are accepted: content-box (W3C) and border-box (traditional model). The traditional model is more intuitive, which has made it the most popular among web developers.

      Here's how to use box-sizing to use the traditional model in your project:

      html ( box-sizing: border-box; ) *, *:before, *:after ( box-sizing: inherit; )

      html (

      box - sizing : border - box ;

      * , * : before , * : after (

      box - sizing : inherit ;

      If you remember things faster when you do things yourself, try experimenting with Guy Routledge's fun interactive demo.

      Setting margin and padding

      You can use the padding-top, padding-right, padding-bottom, and padding-left properties to control the padding on all four sides of an element. Padding can also be specified via a shorthand property. If a single padding value is written, CSS uses it to determine the padding for all 4 sides:

      /* all 4 sides */ padding: 10px;

      If 3 values ​​are presented, the first is responsible for the top, the second for the left and right, and the third for the bottom:

      /* top | horizontal | bottom */ padding: 1em 20px 2em;

      If all 4 values ​​are presented, then each is responsible for top, right, bottom and left, respectively:

      /* top | right | bottom | left */ padding: 10px 10% 2em 15%;

      In the demo below, the orange background is the content area for different elements, the white area between the frame and the content is padding:

      The external margin, like padding, can be controlled on all 4 sides using the properties margin-top, margin-right, margin-bottom and margin-left. You can also set margin for all 4 sides at once using the shorthand property.

      /* all 4 sides */ margin: 10px; /* vertical | horizontal */ margin: 2em 4em; /* top | horizontal | bottom */ margin: 2em auto 2em; /* top | right | bottom | left */ margin: 10px 10% 2em 15%;

      Things to remember Use the correct units of measurement

      When working with padding and margin, avoid absolute units of measurement. Such units do not adapt to changes in font sizes and screen width.

      Let's say you set the element's width to 50% and margin to 15px. At a width of 1200px, the width of the element will be 600px, and the margin will be 15px. At 769px width the element's width will be 384px and the margin will still be 15px.

      The element's width changed by 36%, but its margin remained the same. In most cases this is not the biggest problem. However, if you set the element's margin to a percentage, you will have more control over the page layout on all screens. Everything will look proportional without sudden jumps in the applied margin and padding values.

      Likewise, you might want to add padding to text elements on the page. In most cases, you want the padding to be proportional to the font size on the element. This is impossible to do in absolute units. However, if you set the padding to em, it will automatically adjust to the font size. The demo below shows scaling in action.

      How browsers calculate margin and padding for different units of measurement

      Browsers calculate final margin and padding values ​​differently depending on the units of measurement.

      Margin and padding, specified as a percentage, are calculated relative to the width of the container. That is, 5% padding will be equal to 5px if the container width is 100px, or 50px if the container width is 1000px. Don't forget that the top and bottom values ​​are also calculated based on the width of the container.

      In the case of em, the margin and padding are based on the font size of the element. In the previous demo, the padding on the bottom three text elements is 1em. Due to different font sizes, the calculated padding value will always be different.

      There are also 4 viewport units of measurement vw, vh, vmin and vmax. In this case, the margin and padding values ​​will depend on the viewport. For example, padding 5vw will be equal to 25px with a viewport width of 500px, and padding 10vw will be equal to 50px on the same viewport. You can study these units of measurement in more detail in the article on the SitePoint website “CSS Viewport of Units of Measure: Quick Start”.

      If you're a beginner, knowing how these units work will help you quickly understand why padding and margin on HTML elements change depending on the size of the parent, font, or even viewport. And this will give you the ability to control your layout.

      Collapse of margins

      You also need to know about the concept of collapsing margins. In certain situations, the top and bottom margins on two elements can collapse into one. This phenomenon is called margin collapse.

      Let's say you have two elements one below the other, i.e. on the same level. If you set a margin-bottom of 40px on the first element, and a margin-top of 25px on the second, then the total margin between the elements will not be equal to 65px. The indentation will be equal to the value of the larger margin, i.e. 40px.

      Likewise, the margin can collapse between the parent and the first or last child. This happens if there is no border, padding or inline content separating the child and parent margins. In this case, if there is no padding or border on the parent, the margin of the child element will “flow” from the parent.

      This behavior can be corrected. To do this, you need to add a barrier between the parent and child margins. The demo below shows how adding a border or padding to the parent element can fix the problem.

      In the case of negative margins, the final value of the collapsed margin is equal to the sum of the positive margin with the smallest negative one. You can study the topic of collapsing margins in more detail in the article “Collapsing Margins” by Adam Roberts.

      Interesting ways to use margin and padding

      Sometimes using margin and padding can solve layout problems. Below are some examples:

      Maintain aspect ratio in images

      Often, images on a page have different aspect ratios. If you need to show all images with the same aspect ratio, CSS padding will help you.

      To do this, you need to set the height of the parent to zero, and the padding-top property of the parent should be equal to the aspect ratio value, expressed as a percentage.

      For example, an aspect ratio of 16:9 is achieved by padding: 56.25% 0 0 0. The value 56.25 is obtained by (9/16)*100. Using this method, you can calculate padding percentages for any other aspect ratio.

      Conclusion

      If you're just starting to learn CSS, I hope this tutorial helped you understand the difference between margin and padding. You need to learn how to set margin and padding using abbreviations and appropriate units of measurement. In the last section, I showed two interesting ways to use properties in layouts, and also gave you links to resources for further learning. If you have other tips on CSS margin and padding, please post them in the comments.

      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, CSS margins and 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 when 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 a very convenient thing called margin and padding CSS shorthand. 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: the 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 the CSS margin property. 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 elements are located on top of each other and they 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 differently in different situations:

      • 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 size of the field 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 negative numbers) is selected. 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 CSS units, they are converted to one, after which they are compared and the larger value is selected.
      • The margin size for child elements is determined in an even more interesting way: if a child has a larger margin than its 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.