2023-11-10 10:02:13

边距和填充的区别?

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


当前回答

填充允许开发人员保持文本和它的封闭元素之间的空间。边距是元素与父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>

其他回答

Margin是CSS中的一个属性,用于在元素周围、边框之外创建空格。程序员可以设置上、右、下和左的边距。换句话说,他可以使用margin-top, margin-right, margin-bottom和margin-left来设置这些值。

Margin值可以是以下类型。

首先,auto允许浏览器计算保证金。此外,length表示以px、pt或cm为单位的边距,而%则有助于将边距描述为相对于包含元素宽度的百分比。最后,inherit表示边缘必须从父元素继承。

Padding是CSS中的一个属性,用于帮助在边框内的元素周围创建空间。程序员可以设置上、右、下和左的填充。换句话说,他可以使用padding-top、padding-right、padding-bottom和padding-left来设置这些值。

填充值可以是以下类型。

length以px, pt或cm为单位描述填充,而%则以相对于包含元素宽度的百分比表示填充。最后,inherit表示填充应该继承自父元素。

div.special { width:200px; border-style: solid; border-width:thin; border-color:#000; margin:30px 20px 10px 25px; } div.special2 { width:200px; border-style: solid; border-width:thin; border-color:#000; padding:30px 20px 10px 25px; } <div class="special"> Hello its margin test </div> <div class="special2"> Hello its padding test </div>

边距和填充之间的区别

Margin是一个CSS属性,用于在已定义边框外的元素周围创建空间,而padding是一个CSS属性,用于在已定义边框内的元素周围创建空间。因此,这解释了边距和填充之间的主要区别。

值 此外,margin的值可以是auto、length、%或inherit,而padding的值可以是length、%或inherit type。因此,这是边距和填充之间的另一个区别。

简而言之,边距和填充是CSS中的两个属性,允许对网页进行样式化。不可能为这些属性赋负值。边距和填充之间的主要区别在于边距有助于在边框外的元素周围创建空间,而填充有助于在边框内的元素周围创建空间。

填充是在内容和边框之间计算的。 保证金是在边界外计算的。

Padding是内容和边框之间的空间,而margin是边框之外的空间。这是我从谷歌快速搜索中找到的一张图片,它说明了这个想法。

填充允许开发人员保持文本和它的封闭元素之间的空间。边距是元素与父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>

我对边距和填充的理解来自于谷歌的开发人员工具,如图所示

简单来说,边距是指元素周围的空间,padding指元素和元素内内容之间的空间。 这两种方法都用来制造间隙,但方式不同。

使用Margin创建间隙:

在创建间隙时,边缘将相邻的元素推开

使用Padding创建间隙:

使用填充来创建间隙既可以增加元素的大小,也可以缩小其中的内容

为什么知道两者的区别很重要?

了解它们的区别是很重要的,这样你就可以知道什么时候使用它们,并适当地使用它们。

同样值得注意的是,在设计网站布局时,页边距和填充很方便,因为页边距指定了一个元素是向上还是向下,向左还是向右移动,而填充指定了一个元素在容器内的外观和位置。