2023-11-10 10:02:13

边距和填充的区别?

在CSS中,边距和填充到底有什么区别?它似乎真的没有多大用处。你能给我举个例子说明区别在哪里(以及为什么知道区别很重要)吗?


当前回答

边距和填充之间的一个关键区别在任何答案中都没有提到:点击性和悬停检测

增加填充会增加元素的有效大小。有时我有一个很小的图标,我不想让它看起来更大,但用户仍然需要与该图标进行交互。我增加了图标的填充,让点击和悬停的足迹更大。增加图标的边距不会有同样的效果。

关于这个主题的另一个问题的回答给出了一个例子。

其他回答

Padding是网页上最接近的组件之间的空间,margin是网页边缘的空间。

了解边距和填充之间的区别是很好的。据我所知:

Margin is the outer space of an element, while padding is the inner space of an element. In other words, margin is the space outside of an element's border, while padding is the space inside of its border. You can set auto value to margin. However, it's not allowed for padding. See this. Note: Use margin: auto to center a block element inside its parent horizontally. Also, it's possible to center an element inside a flexbox vertically or horizontally or both, by setting margin to auto. See this. Margin can be any float number, but padding must not be negative. When you style an element, padding will be styled also; but not margin. Margin gets the parent element's style. For example, when you set the background-color property to black, its inner space (i.e. padding) will be black, but not its outer space (i.e. margin).

有一个重要的区别:

边距——位于元素的外部,即在元素开始后应用空格移位。 Padding-在内部,另一个将在元素开始之前应用空白。

边距和填充之间的一个关键区别在任何答案中都没有提到:点击性和悬停检测

增加填充会增加元素的有效大小。有时我有一个很小的图标,我不想让它看起来更大,但用户仍然需要与该图标进行交互。我增加了图标的填充,让点击和悬停的足迹更大。增加图标的边距不会有同样的效果。

关于这个主题的另一个问题的回答给出了一个例子。

填充允许开发人员保持文本和它的封闭元素之间的空间。边距是元素与父DOM中的另一个元素共同维护的空间。

看到的例子:

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