CSS - 高度


CSS 高度属性

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

height属性指定的值由min-heightmax-height属性定义的值获取。

句法

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

长度值

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

百分比值

height: 75%; height: 50%;

关键词值

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

全球价值

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

适用于

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

DOM语法

object.style.height = "100px";

CSS 高度 - 演示

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

CSS 高度 - 长度值

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

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

CSS 高度 - 百分比值

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

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

CSS 高度 - 自动值

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

<html> <head> <style> div.auto { height: auto; background-color: yellow; padding: 20px; margin-bottom: 5px; } </style> </head> <body> <div class="auto">This div element has a height set as auto.</div> </body> </html>

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

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

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

CSS高度-clamp()函数

这使得能够选择在最小和最大高度之间指定的值范围内的中间值。这是使用clamp()函数设置高度的示例:

<html> <head> <style> p{ display: inline-flex; border: 1px solid black; background-color: yellow; height: clamp(20px, 100px, 180px); width: clamp(50px, 100px, 200px); padding: 1em; margin: 2em; } </style> <body> <div> <p>The clamp function is used for height & width, where the background color is selected for the value between the min and max ranges of height and width.</p> </div> </body> </html>