CSS-宽度


CSS 宽度属性

width属性设置元素内容区域的宽度。如果box-sizing设置为border-box,则属性width设置边框区域的宽度。

width属性指定的值保持在min-widthmax-width属性定义的值范围内。

请参阅图像以了解元素的宽度。

宽度

句法

CSS 允许以多种方式设置元素的宽度。让我们检查所有可能的可用语法来设置元素的宽度。

长度值

width: 120px; width: 10em; width: 100vh;

百分比值

width: 75%; width: 50%;

关键词值

width: auto; width: max-content; width: min-content; width: fit-content(20em);

全球价值

width: inherit; width: initial; width: revert; width: revert-layer; width: unset;
不接受像 width: -200px 这样的负值。

适用于

除不可替换的内联元素、表行和行组之外的所有 HTML 元素。

DOM语法

object.style.width = "100px";

CSS 宽度 - 演示

尝试为 CSS宽度属性选择不同的值,并在右侧框中查看结果。

CSS 宽度 - 长度值

CSS 允许将元素的宽度设置为特定的长度值,例如像素 (px)、厘米 (cm)、英寸 (in) 等。下面是以长度单位向div元素添加宽度的示例:

<html> <head> <style> div { border: 1px solid black; margin-bottom: 5px; padding:10px; } div.a { width: 100px; background-color: rgb(230, 230, 203); } div.b { width: 5em; background-color: rgb(230, 230, 203); } </style> </head> <body> <div class="a">This div element has a width of 100px.</div> <div class="b">This div element has a width of 5em.</div> </body> </html>

CSS 宽度 - 百分比值

CSS 允许将元素的高度设置为包含元素的宽度的百分比。以下是向div元素添加宽度(以百分比值表示)的示例:

<html> <head> <style> .parent{ border: 1px solid black; width: 400px; background-color: rgb(230, 230, 203); } .child{ border: 1px solid black; width: 50%; background-color: rgb(76 175 80); } </style> </head> <body> <div class="parent"> <div class="child"> <p>This div element has a 50% width of the parent.</p> </div> </div> </body> </html>

CSS 宽度 - 自动值

这里浏览器会根据内容自动计算宽度。它是元素的默认宽度。以下是向div元素添加宽度为auto的示例:

<html> <head> <style> div { border: 1px solid black; margin-bottom: 5px; } div.auto { width: auto; background-color: yellow; } </style> </head> <body> <div class="auto">This div element has a width set as auto.</div> </body> </html>

CSS 宽度 - 最大内容/最小内容

这是宽度等于max-contentmin-content的示例。最大内容定义了固有的首选宽度,而最小内容定义了固有的最小宽度。

<html> <head> <style> div { border: 1px solid black; margin-bottom: 5px; } div.c { width: max-content; background-color: bisque; } div.d { width: min-content; background-color: darkseagreen; } </style> </head> <body> <div class="c">This div element has a width as max-content.</div> <div class="d">This div element has a width of min-content.</div> </body> </html>

CSS 宽度 - 适合内容

以下是为列表宽度设置的fit-content值的示例:

<html> <head> <style> ul { background-color: beige; width: fit-content; padding: 1.5em; border: 2px solid black; } li { display: inline-flex; background-color: orange; border: 2px solid black; padding: 0.5em; } </style> <body> <ul> <li>Item1</li> <li>Item2</li> <li>Item3</li> <li>Item4</li> </ul> </body> </html>

CSS 宽度 - 相关属性

以下是width相关 CSS 属性列表:

财产 价值
最大宽度 设置元素宽度的上限。
最小宽度 设置元素宽度的下限。