CSS - 尺寸
CSS 尺寸属性定义了网页元素所占据的大小和空间。诸如 height、width、max-height、max-width、line-height 等尺寸属性用于定义 HTML 元素在各种屏幕尺寸下的宽度和高度。在本教程中,我们将学习如何在不同屏幕尺寸下管理 HTML 元素的尺寸和布局。
CSS 设置 height 和 width
height 和 width 属性允许您为定位元素设置特定的高度和宽度。
这些属性可以接受以下值:
- length:任何长度单位(px、pt、em、in 等)
- percentage (%):百分比值,以包含块的高度/宽度的百分比计算。
- auto:浏览器自动计算元素的高度和宽度。(例如,为指定宽度自动设置高度以匹配图像的宽高比)
- initial:将 height 和 width 的值设置为默认值。
- inherit:从父元素继承 height 和 width 的值。
示例
<!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>
padding、margin 和 border 不包含在 height 和 width 中。
设置 Max-Height 和 Max-Width
max-height 和 max-width 属性用于设置元素的最高高度和最大宽度。
- max-width:设置元素的最大宽度。即使内部内容需要更多空间,也会阻止元素超过此宽度。
- max-height:设置元素的最大高度。即使内部内容需要更多空间,也会阻止元素超过此高度。
示例
<!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>
设置 Min-Height 和 Min-Width
min-height 和 min-width 属性用于设置元素的 minimum height 和 width。
- min-width:设置元素的最小宽度。确保元素不会缩小到低于此宽度,即使内容更小。
- min-height:设置元素的最小高度。确保元素不会缩小到低于此高度,即使内容更小。
示例
<!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 尺寸相关属性
所有与 dimensions 相关的属性如下表所示:
| 属性 | 描述 | 示例 |
|---|---|---|
| height | 设置元素的 height。 | Try It |
| width | 设置元素的 width | Try It |
| max-height | 设置元素的最大 height | Try It |
| min-height | 设置元素的最小 height。 | Try It |
| max-width | 设置元素的最大 width。 | Try It |
| min-width | 设置元素的最小 width。 | Try It |