CSS - 边距

margin 属性定义HTML元素周围的空间.可以使用负值来重叠内容.

子元素不会继承margin属性的值.请记住,相邻的垂直边距(顶部和底部边距)将相互折叠,使得块之间的距离不是边距的总和,而是仅两个边距中的较大者或者如果两者都是一个边距的相同尺寸等于.

我们有以下属性来设置元素边距.

  • 边距指定一个简写属性,用于在一个声明中设置边距属性.

  • margin-bottom 指定元素的下边距.

  • margin-top 指定元素的上边距.

  • margin-left 指定元素的左边距.

  • margin-right 指定元素的右边距.

现在,我们将看到如何将这些属性与示例一起使用.

保证金属性

保证金属性允许您设置所有专业人员在一个声明中涉及四个边际.以下是围绕段落设置边距的语法;

这是一个示例 :

<html>
   <head>
   </head>
   
   <body>
      <p style = "margin: 15px; border:1px solid black;">
         all four margins will be 15px
      </p>
      
      <p style = "margin:10px 2%; border:1px solid black;">
         top and bottom margin will be 10px, left and right margin will be 2% 
         of the total width of the document.
      </p>
      
      <p style = "margin: 10px 2% -10px; border:1px solid black;">
         top margin will be 10px, left and right margin will be 2% of the 
         total width of the document, bottom margin will be -10px
      </p>
      
      <p style = "margin: 10px 2% -10px auto; border:1px solid black;">
         top margin will be 10px, right margin will be 2% of the total 
         width of the document, bottom margin will be -10px, left margin 
         will be set by the browser
      </p>
   </body>
</html>

The margin-bottom Property

margin-bottom属性允许您设置元素的下边距。 它可以有一个长度值,%或auto。

这是一个例子:

<html>
   <head>
   </head>

   <body>
      <p style = "margin-bottom: 15px; border:1px solid black;">
         This is a paragraph with a specified bottom margin
      </p>
      
      <p style = "margin-bottom: 5%; border:1px solid black;">
         This is another paragraph with a specified bottom margin in percent
      </p>
   </body>
</html>

The margin-top Property

margin-top属性允许您设置元素的上边距。 它可以有一个长度值,%或auto。

这是一个例子: 

<html>
   <head>
   </head>

   <body>
      <p style = "margin-top: 15px; border:1px solid black;">
         This is a paragraph with a specified top margin
      </p>
      
      <p style = "margin-top: 5%; border:1px solid black;">
         This is another paragraph with a specified top margin in percent
      </p>
   </body>
</html>

The margin-left Property

margin-left属性允许您设置元素的左边距。 它可以有一个长度值,%或auto。

这是一个例子:

 

<html>
   <head>
   </head>

   <body>
      <p style = "margin-left: 15px; border:1px solid black;">
         This is a paragraph with a specified left margin
      </p>
      
      <p style = "margin-left: 5%; border:1px solid black;">
         This is another paragraph with a specified top margin in percent
      </p>
   </body>
</html>

The margin-right Property

margin-right属性允许您设置元素的右边距。 它可以有一个长度值,%或auto。

这是一个例子:

<html>
   <head>
   </head>
   
   <body>
      <p style = "margin-right: 15px; border:1px solid black;">
         This is a paragraph with a specified right margin
      </p>
      <p style = "margin-right: 5%; border:1px solid black;">
         This is another paragraph with a specified right margin in percent
      </p>
   </body>
</html>