当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。