CSS 中的 max-width 属性

cssweb developmentfront end technology更新于 2025/1/7 2:52:17

我们可以使用 CSS max-width 属性为元素的内容框定义一个固定的最大宽度,即使 width 大于 max-width,元素的内容框也不会变得更宽。

语法

CSS max-width 属性的语法如下 −

Selector {
   max-width: /*value*/
}

让我们看一个 CSS max-width 属性的例子 −

示例

<!DOCTYPE html>
<html>
<head>
<title>CSS max-width Property</title>
</head>
<style>
* {
   padding: 2px;
   margin:5px;
}
button {
   border-radius: 10px;
}
#containerDiv {
   width:70%;
   margin: 0 auto;
   padding:20px;
   background-image: linear-gradient(135deg, #dc3545 0%, #9599E2 100%);
   text-align: center;
   border-radius: 10px;
}
#contentDiv{
   max-width:200px;
   overflow: hidden;
}
</style>
<body>
<div id="containerDiv">
<div id="contentDiv">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
</div>
<button onclick="add()" class="btn">Set maxWidth</button>
</div>
<script>
function add() {
   document.querySelector('#contentDiv').style.maxWidth = "100%";
}
</script>
</body>
</html>

输出

点击"设置最大宽度"按钮之前 −

点击"设置最大宽度"按钮之后 −

让我们看另一个关于 CSS max-width 属性的示例 −

示例

<!DOCTYPE html>
<html>
<head>
<title>CSS max-width Property</title>
</head>
<style>
* {
   padding: 2px;
   margin:5px;
}
button {
   border-radius: 10px;
}
#containerDiv {
   width:70%;
   margin: 0 auto;
   padding:20px;
   background-image: linear-gradient(135deg, #dc3545 0%, #9599E2 100%);
   text-align: center;
   border-radius: 10px;
}
#contentDiv1, #contentDiv2{
   width:100%;
   border: 1px solid black;
   margin: 0 auto;
}
#contentDiv2{
   width: 80%;
}
</style>
<body>
<div id="containerDiv">
<div id="contentDiv1">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
</div>
<div id="contentDiv2">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy.
</div>
<button onclick="add()" class="btn">Set maxWidth</button>
</div>
<script>
function add() {
   document.querySelector('#contentDiv1').style.maxWidth = "80%";
}
</script></body></html>

输出

点击"设置最大宽度"按钮之前 −

点击"设置最大宽度"按钮之后 −


相关文章


有用资源