What is margin padding? PADDING and MARGIN properties and how to use them


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, which should not be interconnected during layout. 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 ability to add any required number of 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 two rules tested from my own experience. So, let's use:

    padding - for spaces between the container and its content.

    margin - for spaces between elements inside the container.

    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 some block is given margin-left and margin-right with auto values, then if the block has fixed width(for example 400px) and there is no 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 border - 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!

    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

    CSS margin property defines the distance around the 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.

    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.

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





    

    2024 gtavrl.ru.