CSS - 尺寸



CSS 尺寸定義網頁元素的大小和佔據的空間。尺寸屬性例如高度、寬度、最大高度、最大寬度、行高等等,用於定義各種螢幕尺寸下HTML元素的寬度和高度。在本教程中,我們將學習如何在不同螢幕尺寸下管理HTML元素的尺寸和佈局。

CSS 設定高度和寬度

heightwidth 屬性允許您為定位元素設定特定的高度和寬度。

這些屬性可以包含以下值:

  • 長度:任何長度單位(px、pt、em、in 等)。
  • 百分比 (%):百分比值,表示包含塊高度/寬度的百分比。
  • auto:瀏覽器計算元素的高度和寬度。(例如,為指定寬度設定高度以匹配影像的縱橫比)
  • initial:將高度和寬度的值設定為其預設值。
  • inherit:從其父元素繼承高度和寬度的值。

示例

<!DOCTYPE html>
<html>

<head>
    <style>
        div {
            height: 100px;
            width: 80%;
            background-color: rgb(206, 211, 225);
        }
        img{
            height: auto;
            width: 180px;
        }
    </style>
</head>

<body>
    <h1>Height and Width Property</h1>
    <h2>Length and percentage values</h2>
    <div>
        This div element has a height of 50px and a width 
        of 80%.
    </div>

    <h2>Auto value</h2>
    <img src="/css/images/logo.png"/>
    <br>
    Height is this image adjusted for width 180px so that 
    aspect ratio is maintained.
</body>
</html>
內邊距、外邊距邊框不包含在高度和寬度中。

設定最大高度和最大寬度

max-heightmax-width 屬性用於設定元素的最大高度和寬度。

  • max-width:設定元素可以達到的最大寬度。即使內部內容需要更多空間,也防止元素超過此寬度。
  • max-height:設定元素可以達到的最大高度。即使內部內容需要更多空間,也防止元素超過此高度。

示例

<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        .container {
            width: 90%;
            margin: 0 auto;
            text-align: center;
        }
        
        img{
            max-width: 100%;
            max-height: 400px;
            height: auto;
        }

    </style>
</head>
<body>
    <div class="container">
        <img src="/css/images/logo.png" >
        <p>
            This image has a maximum width and height set. 
            Resize the browser window to see how the image 
            scales down.
        </p>
    </div>
</body>
</html>

設定最小高度和最小寬度

min-heightmin-width 屬性用於設定元素的最小高度和寬度。

  • min-width:設定元素可以達到的最小寬度。即使內容較小,也確保元素不會縮小到此寬度以下。
  • min-height:設定元素可以達到的最小高度。即使內容較小,也確保元素不會縮小到此高度以下。

示例

<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        .container {
            width: 90%;
            margin: 0 auto;
            text-align: center;
        }
        
        .box {
            min-width: 300px;
            min-height: 200px;
            background-color: #f0f0f0;
            padding: 20px;
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="box">
            This box has a minimum width and height set. 
            Resize the browser window to see how the box 
            does not shrink below the specified dimensions.
        </div>
    </div>
</body>
</html>

CSS 尺寸相關屬性

下表列出了所有與尺寸相關的屬性

屬性 描述 示例
height 設定元素的高度。
width 設定元素的寬度
max-height 設定元素的最大高度
min-height 設定元素的最小高度。
max-width 設定元素的最大寬度。
min-width 設定元素的最小寬度。
廣告