3.1 屬性 width
CSS 中的區塊大小在 web 頁面佈局中扮演重要角色。它們決定了元素如何顯示以及與周圍元素的互動。我們現在來看看 width
、height
、max-width
和 max-height
等屬性,這些屬性允許設置區塊的大小。
屬性 width
設定元素的寬度。它可以用多種單位設置,如像素 (px
)、百分比(%
)、em
、rem
等。
值
- 自動值:
auto
— 元素的寬度自動由其內容和環境決定 - 絕對單位:
px
、pt
、cm
、mm
、in
等 - 相對單位:
%
、em
、rem
、vw
、vh
等
使用範例:
CSS
.box {
background-color: #3498db;
color: white;
padding: 10px;
margin: 10px;
}
.box-fixed {
width: 200px;
}
.box-percentage {
width: 50%;
}
HTML
<div class="box box-fixed">固定寬度 (200px)</div>
<div class="box box-percentage">百分比寬度 (50%)</div>
代碼解釋:
.box-fixed
:元素具有固定寬度 200 像素.box-percentage
:元素寬度為父元素的 50%
3.2 屬性 height
屬性 height
設定元素的高度。它也可以用多種單位設置。
值:
- 自動值:
auto
— 元素的高度自動由其內容和環境決定 - 絕對單位:
px
、pt
、cm
、mm
、in
等 - 相對單位:
%
、em
、rem
、vh
、vw
等
使用範例:
CSS
.container {
height: 300px;
}
.box {
color: white;
padding: 10px;
}
.box-fixed-height {
height: 150px;
background-color: #2ecc71;
}
.box-percentage-height {
height: 50%;
background-color: #7a5c71;
}
HTML
<div class="container">
<div class="box box-fixed-height">固定高度 (150px)</div>
<div class="box box-percentage-height">百分比高度 (50%)</div>
</div>
代碼解釋:
.box-fixed-height
:元素具有固定高度 150 像素.box-percentage-height
:元素高度為父元素的 50%
3.3 屬性 max-width
屬性 max-width
設定元素的最大寬度。這是一個限制,可防止元素超出設定值的範圍。
值:
- 無限制:
none
— 元素可以擴展到任何寬度 - 絕對單位:
px
、pt
、cm
、mm
、in
等 - 相對單位:
%
、em
、rem
、vh
、vw
等
使用範例:
CSS
.box {
background-color: #e74c3c;
color: white;
padding: 10px;
margin: 10px;
}
.box-max-width {
width: 100%;
max-width: 300px;
}
HTML
<div class="box">寬度 100% (預設)</div>
<div class="box box-max-width">最大寬度 300px</div>
代碼解釋:
.box-max-width
:元素最大寬度 300 像素。內容不允許元素超出 300 像素的範圍
3.4 屬性 max-height
屬性 max-height
設定元素的最大高度。這是一個限制,可防止元素超出設定值的範圍。
值:
- 無限制:
none
— 元素可以擴展到任何寬度 - 絕對單位:
px
、pt
、cm
、mm
、in
等 - 相對單位:
%
、em
、rem
、vh
、vw
等
使用範例:
CSS
.box {
background-color: #9b59b6;
color: white;
padding: 10px;
max-height: 35px;
overflow: auto;
}
HTML
<div class="box">
<p>用於展示滾動的額外文本。<br>用於展示滾動的額外文本。<br>用於展示滾動的額外文本。</p>
</div>
代碼解釋:
.box-max-height
:元素最大高度 100 像素。如果內容超過此值,因overflow: auto;
屬性,它將可滾動
GO TO FULL VERSION