使用CSS設定單個邊距


CSS允許我們控制元素各個邊的周圍空間。CSS margin屬性是以下屬性的簡寫:margin-top、margin-right、margin-bottom和margin-left。

語法

CSS margin屬性的語法如下:

Selector {
   margin-top: /*value*/
   margin-right: /*value*/
   margin-bottom: /*value*/
   margin-left: /*value*/
}

值可以是以下之一:

  • 長度 - 以px、pt等設定邊距。預設為0

  • % - 以百分比設定邊距

  • auto - 網頁瀏覽器自動計算邊距

假設我們使用簡寫屬性設定了以下邊距:

margin: 25px 30px 50px 60px;

以上表示:

  • 頂部邊距為25畫素

  • 右側邊距為30畫素

  • 底部邊距為50畫素

  • 左側邊距為60畫素

我們可以這樣設定單個邊的邊距:

margin-top: 25px;
margin-right: 30px;
margin-bottom: 50px;
margin-left: 60px;

以下示例說明了CSS margin屬性:

設定margin auto

使用值為auto的margin屬性,邊距由網頁瀏覽器自動調整:

margin-left: auto;

示例

讓我們來看一個例子:

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin-left: auto;
         margin-bottom: 4em;
         width: 30%;
         padding: 0.6rem;
         box-shadow: inset 0 0 3px turquoise;
         outline: thin dotted;
         text-align: center;
      }
      div + div {
         margin-right: 30%;
         box-shadow: inset 0 0 6px teal;
      }
      div + div + div {
         margin-left: 45%;
         margin-top: -190px;
         box-shadow: inset 0 0 6px orange;
      }
   </style>
</head>
<body>
   <div>
      This is demo text
   </div>
   <div>One (different margins)</div>
   <div>Two (different margins)</div>
</body>
</html>

為div設定邊距

這裡,我們為網頁上的多個容器設定了邊距:

margin-top: 7%;
margin-left: 25%;

我們也設定了負值:

margin-bottom: -3em;

示例

讓我們來看一個例子:

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         margin-top: 7%;
         margin-left: 25%;
         margin-bottom: -3em;
         width: 40px;
         height: 40px;
         padding: 0.6rem;
         box-shadow: inset 0 0 3px turquoise;
         border-top-right-radius: 100px;
      }
      div + div {
         margin-right: 30%;
         border-top-right-radius: unset;
         border-top-left-radius: 100px;
         box-shadow: inset 0 0 6px teal;
      }
      div + div + div {
         margin-left: 25%;
         margin-top: -140px;
         box-shadow: inset 0 0 6px orange;
         border-bottom-right-radius: 100px;
      }
   </style>
</head>
<body>
   <div></div>
   <div></div>
   <div></div>
</body>
</html>

更新於:2023-12-27

231 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告