當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


CSS max-width屬性用法及代碼示例

有時將元素的寬度限製在某個範圍內很有用。有兩個屬性 max-width 和 min-width 用於設置元素的最大和最小寬度。

CSS 中的 max-width 屬性用於設置元素內容框的最大寬度。這意味著內容框的寬度可以小於 max-width 值,但不能大於。它設置元素寬度的上限。

當內容大於最大寬度時,它會自動改變元素的高度。如果內容小於 max-width,則該屬性無效。該屬性確保寬度屬性的值不能大於 max-width 屬性的值。它不允許負值。

用法

max-width:none | length | initial | inherit;

此 CSS 屬性的值定義如下。

none:它是不限製內容框寬度的默認值。

length:該值定義了 max-width 的長度,單位為 px、cm、pt 等。

initial:它將屬性設置為其默認值。

inherit:它從其父元素繼承屬性。

現在,讓我們看一個這個 CSS 屬性的例子。

示例

在這個例子中,有四個帶有內容的段落元素。我們使用 max-width 屬性的長度值定義這些段落的 maximum-width。第一段最大寬度175px,第二段20em,第三段350pt,第四段10cm。

第一段的內容大於 max-width 屬性的值,所以在輸出中,我們可以看到第一段的高度自動改變了。

<!DOCTYPE html>
<html>
<head>
<title>
max-width property
</title>

<style>
p{
border:4px solid blue;
background-color:lightblue;
font-size:20px;
}
#px {
max-width:175px;
}
#em {
max-width:20em;
}
#pt {
max-width:350pt;

}
#cm {
max-width:10cm;

}
</style>
</head>
<body>
<h2> max-width:175px; </h2>
<p id = "px">
Hi, Welcome to the javaTpoint.com. This site is developed so that students may learn computer science related technologies easily. The javaTpoint.com is always providing an easy and in-depth tutorial on various technologies. No one is perfect in this world, and nothing is eternally best. But we can try to be better.
</p>
<h2> max-width:20em; </h2>
<p id = "em">
Hi, Welcome to the javaTpoint.com. This site is developed so that students may learn computer science related technologies easily. The javaTpoint.com is always providing an easy and in-depth tutorial on various technologies. No one is perfect in this world, and nothing is eternally best. But we can try to be better.
</p>
<h2> max-width:350pt; </h2>
<p id = "pt">
Hi, Welcome to the javaTpoint.com. This site is developed so that students may learn computer science related technologies easily. The javaTpoint.com is always providing an easy and in-depth tutorial on various technologies. No one is perfect in this world, and nothing is eternally best. But we can try to be better.
</p>
<h2> max-width:10cm; </h2>
<p id = "cm">
Hi, Welcome to the javaTpoint.com. This site is developed so that students may learn computer science related technologies easily. The javaTpoint.com is always providing an easy and in-depth tutorial on various technologies. No one is perfect in this world, and nothing is eternally best. But we can try to be better.
</p>

</body>
</html>

輸出

CSS max-width property



相關用法


注:本文由純淨天空篩選整理自 CSS max-width property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。