Difference between margin and padding?

2018-12-31 21:30发布

What exactly is the difference between margin and padding in CSS? It really doesn't seem to serve much purpose. Could you give me an example of where the differences lie (and why it is important to know the difference)?

标签: css
19条回答
不再属于我。
2楼-- · 2018-12-31 21:40

Margin and padding are both types of padding really....One (margin) goes outside of the elements border to distance it from other elements and the other (padding) goes outside of the elements content to distance the content from the elements border.

查看更多
孤独寂梦人
3楼-- · 2018-12-31 21:40

Padding allows the developer to maintain space between the text and it's enclosing element. Margin is the space that the element maintains with another element of the parent DOM.

See example:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UT-8">
    <title>Pseudo Elements</title>
    <style type="text/css">
        body{font-family:Arial; font-size:16px; background-color:#f8e6ae; color:#888;}
        .page
        {
            background-color: #fff;
            padding: 10px 30px 50px 50px;
            margin:30px 100px 30px 300px;
        }
    </style>
</head>
<body>
    <div class="page">
        Notice the distance between the top and this text. Then compare it with the distance between the bottom border and the this text. 
    </div>
</body>
查看更多
素衣白纱
4楼-- · 2018-12-31 21:42

Remember these 3 points:

  • The Margin is the extra space around the control.
  • The Padding is extra space inside the control.
  • The Padding of an outer control is the Margin of an inner control.

Demo Image:(where red box is desire control) enter image description here

查看更多
冷夜・残月
5楼-- · 2018-12-31 21:42

The simplest defenition is ; padding is a space given inside the border of the container element and margin is given outside. For a element which is not a container, padding may not make much sense, but margin defenitly will help to arrange it.

查看更多
荒废的爱情
6楼-- · 2018-12-31 21:46

One key thing that is missing in the answers here:

Top/Bottom margins are collapsible.

So if you have a 20px margin at the bottom of an element and a 30px margin at the top of the next element, the margin between the two elements will be 30px rather than 50px. This does not apply to left/right margin or padding.

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 21:46

Try putting a background color on a block div with width and height. You'll see that padding increases the size of the element, whereas margin just moves it within the flow of the document.

Margin is specifically for shifting the element around.

查看更多
登录 后发表回答