Css padding margin difference. PADDING and MARGIN properties and how to use them. Box model in CSS - padding, margin and border

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 margin properties-right, padding-right, margin-bottom, padding-bottom - they are for padding 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!

Let's see the difference between margin and padding. To do this, let’s remember once again the block model in CSS.

MARGIN (Margin) is the distance from the border (frame) of the block, to the nearest elements, or, if there are none, to the edges of the document.

PADDING (Indents) - like an internal distance between the border (frame) and the contents of the block.

Example: Let's create three styles for three different paragraphs, with different margin and padding values, and look at the result:

Those. values ​​are written clockwise: top, right, bottom, left.

In what cases is it better to use indentation and in what cases is it better to use margins?

A few key differences:

    Indents (padding) are located inside the block, and margins (margin) are located outside them;

    The block background and background image only apply to padding, not margins. Margins are always transparent, allowing the background of the parent element to show through.

14. Height and width of blocks

By default, the height and width of blocks are determined automatically, i.e. the more text (or other content) the wider and higher the block.

But, using CSS technology, we can set the width and height of the blocks we need.

HEIGHT – property that sets the height of the block;

WIDTH – property that sets the width of the block;

Typically, DIV elements are used as blocks in CSS. However, the width and height properties can also be applied to paragraphs, lists, etc.

Let's create 4 classes and assign them one by one to the same box (in in this case DIV ) with text.

Now the height is fixed, and the width is stretched to fit the content.

.box3 ( width: 300px; height: 600px; border: 1px solid red; background: #FFE446; )

Here both the height and width are fixed.

.box4 ( width: 300px; height: 300px; border: 1px solid red; background: #FFE446; )

And this is an example of what a box with a fixed width and height will look like if the content does not fit. The text simply goes beyond the block.

Note!

Thus, by specifying the width of a block, you are specifying the width of only that part of the block that is reserved for content.

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're talking about, the diagram below is shown.

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 lead to unexpected consequences for 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 most a big 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. Because of different sizes font, 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, 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 to add a border or padding to parent element allows you to fix the problem.

In the case of negative margins final value 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 margin and padding can help 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 applying 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.

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 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 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. The top and bottom margins behave differently than the side margins; if two margins are placed on top of each other, they will 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 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.

    In the previous chapter we mentioned such CSS properties, like margin (field) and padding (indent). 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 when there is no frame or background of the content block.

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