CSS Margin边距

CSS margin 属性用于在元素周围创建空间。
CSS 提供了不同的属性,在这些属性的帮助下,我们可以设置元素每一边(右侧、左侧、顶部和底部)的边距。

Margin作为速记属性

CSS 边距属性margin是以下各个边距属性的简写属性:

  • margin-top
  • margin-bottom
  • margin-left
  • margin-right

当 margin 属性有四个不同的值时,它在代码中看起来像这样:

p {
  margin-top: 25px;
  margin-right: 10px;
  margin-bottom: 15px;
  margin-left: 20px;
}

如果所有边都有相同的值,例如所有边都是50px,在CSS中我们可以这样写。

p {
  margin: 50px;
}

当顶部和底部的值相同(例如 15px)并且左侧和右侧的值相同(例如 10px)时,我们可以执行以下代码。

p {
  margin: 15px 10px;
}

这和这个是一样的。

p {
  margin-top: 15px;
  margin-right: 10px;
  margin-bottom: 15px;
  margin-left: 10px;
}

当左右边的值相同时,例如15px,上边是5px,下边是10px,我们会写下面的代码。

p {
  margin: 5px 15px 10px;
}

这和这个是一样的。

p {
  margin-top: 5px;
  margin-right: 15px;
  margin-bottom: 10px;
  margin-left: 15px;
}

边距属性示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        background-color: #1c87c9;
        color: white;
        margin: 25px 10px 15px 20px;
      }
    </style>
  </head>
  <body>
    <p>Paragraph with background-color, color and margin properties.</p>
  </body>
</html>

margin 属性的继承值

在下面的示例中,<p> 元素的左边距是从其父元素 (<div>) 继承而来的:

具有“继承”值的边距属性示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        background-color: lightblue;
        margin-left: 100px;
      }
      p.inherit {
        margin-left: inherit;
        padding: 10px 0;
      }
    </style>
  </head>
  <body>
    <h2>The inherit value</h2>
    <p>
      Here the left margin is inherited from its parent element:
    </p>
    <div>
      <p class="inherit">
        With the help of the "inherit" value, the left margin is inherited from the div element.
      </p>
    </div>
  </body>
</html>

独立边距

借助以下属性,我们可以为元素的每一侧设置边距:

  • margin-top
  • margin-bottom
  • margin-left
  • margin-right

很明显,对于顶部,我们使用 margin-top,对于底部 使用 margin-bottom,对于左侧使用 margin-left 和右侧使用 margin-right。

所有边距属性都可以具有以下值:

  • auto - 保证金由浏览器计算,
  • length,用于指定以 px、pt、cm 等为单位的边距,
  • %,它指定包含元素宽度的 % 的边距,
  • inherit ,它指定边距必须从其父元素继承。

margin 属性接受负值。

margin 属性的 auto 值

设置 margin 属性的“auto”值,我们可以在其容器内水平居中元素。
结果,元素将占据定义的宽度,剩余的空间将在左右边距之间划分。

带有“auto”值的边距属性示例:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      div {
        width: 300px;
        margin: auto;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <h2>The auto value</h2>
    <p>
      设置 margin 属性的“auto”值,您可以在其容器内水平居中元素。 结果,元素将占据定义的宽度,剩余的空间将在左右边距之间划分。
    </p>
    <div>
      auto 值使此 div水平居中。
    </div>
  </body>
</html>
日期:2020-06-02 22:14:26 来源:oir作者:oir