HTML DOM Style maxWidth 属性

htmlweb developmentfront end technology更新于 2025/6/9 1:16:17

DOM Style maxWidth 属性用于返回并修改 HTML 文档中元素的最大宽度。

语法

以下是语法 −

  • 返回 maxWidth

object.style.maxWidth
  • 修改 maxWidth

object.style.maxWidth = “value”

值

此处,值可以为 -

值说明
None不限制元素宽度。
inherit从其父元素继承此属性值。
initial将此属性值设置为其默认值。
length以宽度单位设置值。
percentage(%)以父元素的百分比宽度设置值。

示例

让我们看一个 Style maxWidth 属性的示例 −

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      color: #000;
      background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%);
      height: 100vh;
   }
   p {
      border: 2px solid #fff;
   }
   .btn {
      background: coral;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 40%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
   }
</style>
</head>
<body>
<h1>DOM Style maxWidth Property Example</h1>
<p>
   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.
</p>
<button onclick="add()" class="btn">Set maxWidth</button>
<script>
   function add() {
      document.querySelector('p').style.maxWidth = "200px";
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

点击“设置最大宽度”按钮设置段落元素的最大宽度 −


相关文章


有用资源