CSS - margin-top 屬性



margin-top 屬性設定元素頂部外邊距的寬度。

正值將其與相鄰元素隔開,而負值則將其拉近。

可能的值

以下列表包含 margin-top 屬性的所有可能值。

  • <length> - 外邊距大小的固定值。

  • <percentage> - 外邊距的百分比,相對於包含塊的內聯尺寸,或在水平語言中 writing-mode 定義的寬度。

  • auto - 瀏覽器會自行選擇一個合適的值。

應用於

所有元素,除了具有除 table-captiontableinline-table 之外的表格 display 型別的元素。它也適用於 ::first-letter

語法

margin-top = <length-percentage> | auto   

CSS margin-top - 基本示例

以下示例顯示了可以傳遞給 margin-top CSS 屬性的不同值

<html>
<head>
<style>
   p {
      background-color: rgb(201, 238, 240);
      border: 1px solid black;
      width: fit-content;
   }

   .margin-px {
      margin-top: 30px;
   }

   .margin-perc {
      margin-top: 10%;
   }

   .margin-em {
      margin-top: 3em;
   }

   .margin-auto {
      margin-top: auto;
   }

   .margin-neg {
      margin-top: -10px;
   }
</style>
</head>
   
<body>
   <p class="margin-px">
      The top margin is 30px.
   </p>
   
   <p class="margin-perc">
      The top margin is 10%.
   </p>
   
   <p class="margin-em">
      The top margin is 3em.
   </p>
   
   <p class="margin-auto">
      The top margin will be set by the browser.
   </p>
   
   <p class="margin-neg">
      The top margin is -10px.
   </p>
</body>
</html>

inherit - 當您希望子元素的頂部外邊距與其父元素的頂部外邊距匹配時,使用 inherit 屬性。

注意:inherit 值只能用於子元素,不能用於父元素。

CSS margin-top - 繼承

這是一個子元素的 margin-top 繼承自父元素的示例:

<html>
<head>
<style>
   .p {
      margin-top: 20%;
   }
   
   p.example {
      margin-top: inherit;
      border: 1px solid #4CAF50;
   }
</style>
</head>
<body>
<h3>margin-top property - inherit</h3> 
   <p>The margin-top is 20% for parent element.</p>
   <p class="example">A child element where the top margin is inherited from the parent (p) and is 20%.</p>
</body>
</html>
廣告

© . All rights reserved.