CSS - 尺寸



CSS 尺寸定义网页元素的大小和占据的空间。尺寸属性例如高度、宽度、最大高度、最大宽度、行高等等,用于定义各种屏幕尺寸下HTML元素的宽度和高度。在本教程中,我们将学习如何在不同屏幕尺寸下管理HTML元素的尺寸和布局。

CSS 设置高度和宽度

heightwidth 属性允许您为定位元素设置特定的高度和宽度。

这些属性可以包含以下值:

  • 长度:任何长度单位(px、pt、em、in 等)。
  • 百分比 (%):百分比值,表示包含块高度/宽度的百分比。
  • auto:浏览器计算元素的高度和宽度。(例如,为指定宽度设置高度以匹配图像的纵横比)
  • initial:将高度和宽度的值设置为其默认值。
  • inherit:从其父元素继承高度和宽度的值。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> div { height: 100px; width: 80%; background-color: rgb(206, 211, 225); } img{ height: auto; width: 180px; } </style> </head> <body> <h1>Height and Width Property</h1> <h2>Length and percentage values</h2> <div> This div element has a height of 50px and a width of 80%. </div> <h2>Auto value</h2> <img src="/css/images/logo.png"/> <br> Height is this image adjusted for width 180px so that aspect ratio is maintained. </body> </html>
内边距、外边距边框不包含在高度和宽度中。

设置最大高度和最大宽度

max-heightmax-width 属性用于设置元素的最大高度和宽度。

  • max-width:设置元素可以达到的最大宽度。即使内部内容需要更多空间,也防止元素超过此宽度。
  • max-height:设置元素可以达到的最大高度。即使内部内容需要更多空间,也防止元素超过此高度。

示例

Open Compiler
<!DOCTYPE html> <html lang="en"> <head> <style> .container { width: 90%; margin: 0 auto; text-align: center; } img{ max-width: 100%; max-height: 400px; height: auto; } </style> </head> <body> <div class="container"> <img src="/css/images/logo.png" > <p> This image has a maximum width and height set. Resize the browser window to see how the image scales down. </p> </div> </body> </html>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

设置最小高度和最小宽度

min-heightmin-width 属性用于设置元素的最小高度和宽度。

  • min-width:设置元素可以达到的最小宽度。即使内容较小,也确保元素不会缩小到此宽度以下。
  • min-height:设置元素可以达到的最小高度。即使内容较小,也确保元素不会缩小到此高度以下。

示例

Open Compiler
<!DOCTYPE html> <html lang="en"> <head> <style> .container { width: 90%; margin: 0 auto; text-align: center; } .box { min-width: 300px; min-height: 200px; background-color: #f0f0f0; padding: 20px; } </style> </head> <body> <div class="container"> <div class="box"> This box has a minimum width and height set. Resize the browser window to see how the box does not shrink below the specified dimensions. </div> </div> </body> </html>

CSS 尺寸相关属性

下表列出了所有与尺寸相关的属性

属性 描述 示例
height 设置元素的高度。
width 设置元素的宽度
max-height 设置元素的最大高度
min-height 设置元素的最小高度。
max-width 设置元素的最大宽度。
min-width 设置元素的最小宽度。
广告