CSS 資料型別 - <percentage>



CSS 的<percentage>資料型別表示另一個值的比例,通常相對於父元素或其他參考值。百分比經常用於各種 CSS 屬性(例如font-sizewidthheightmarginpadding)來指定尺寸、間距或其他比例值。

語法

<number>%

一個<number>和百分號 (%) 構成<percentage>資料型別。可選地在前面新增一個 + 或 - 符號,但並非所有屬性都允許負值。與其他尺寸型別不同,CSS 尺寸在符號和數字之間沒有空格。

CSS <percentage> - 字型大小

以下示例演示了使用<percentage>資料型別來設定字型大小。

 <html>
<head>
<style>
   body, html {
      margin: 0;
      padding: 0;
   }
   .container {
      width: 90%; /* Set container width to 90% of the viewport width */
      background-color: #f0f0f0;
      margin: 40px auto; 
   }
   .text {
      font-size: 100%; /* Default font size (16px) */
      text-align: center;
      margin: 20px 0;
   }
   .text-smaller {
      font-size: 80%; /* Font size 80% of the default size */
      color: red;
   }
   .text-larger {
      font-size: 120%; /* Font size 120% of the default size */
      color: blue;
   }
</style>
</head>
<body>
<div class="container">
   <p class="text">Font Size with Percentage</p>
   <p class="text text-smaller">Smaller Font Size</p>
   <p class="text text-larger">Larger Font Size</p>
</div>
</body>
</html>

CSS <percentage> - 盒子大小

以下示例演示了使用<percentage>資料型別來改變容器和盒子的尺寸。

<html>
<head>
<style>
   body, html {
      margin: 0;
      padding: 0;
   }  
   .container {
      width: 70%; /* Set container width to 70% of the viewport width */
      margin: 20px auto; 
      background-color: #f4f4f4; 
      padding: 20px; 
   }   
   .box {
      width: 40%; /* Box width set to 40% of its container */
      height: 200px;
      background-color: #3498db; 
      color: white;
      text-align: center;
      line-height: 200px;
      margin: 0 auto 20px; 
   }
   .box:nth-child(2) {
      width: 60%; /* Box width set to 60% of its container */
      height: 160px;
      background-color: #e74c3c; 
      line-height: 160px;
   }
</style>
</head>
<body>
<div class="container">
<div class="box">
   <p>Box 1 - 40% of container width</p>
</div>
<div class="box">
   <p>Box 2 - 60% of container width</p>
</div>
</div>
</body>
</html>
廣告