抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

固有尺寸

在受CSS设置影响之前,HTML元素有其原始的尺寸。一个直观的例子就是图像,图像的长宽由这个图像文件自身确定,这个尺寸就是固有尺寸。如果将图片放置在网页中的时候没有在标签或CSS中设置其尺寸,那么将使用其固有尺寸显示。

1
2
3
4
5
6
7
<img src="star.png" alt="star"/>

<style>
img {
border: 5px solid darkblur;
}
</style>

设置具体的尺寸

当给元素指定尺寸时,将其称为外部尺寸。
下面的例子中,给div一个具体的width和height,然后不论我们放什么进去他都是该尺寸。如果内容的数量超出了元素可容纳的空间,则设置的高度会导致内容溢出

1
2
3
4
5
6
7
8
9
10
11
12
<div class="wrapper">
<div class="box"></div>
<div class="box">These boxes both have a height set, this box has content in it which will need more space than the assigned height, and so we get overflow. </div>
</div>

<style>
.box {
border: 5px solid darkblue;
height: 150px;
width: 200px;
}
</style>

使用百分比

百分比是长度单位,通常可以于长度互换。当使用百分比的时候,需要清楚它是哪个值的百分比。

1
2
3
4
5
6
7
8
9
10
11
<div class="box">
I have a percentage width.
</div>

<style>
.box {
border: 5px solid darkblue;
/* 父容器的百分比作为宽度 */
width: 50%;
}
</style>

百分比作为内外边距

如果把margin和padding设置为百分比,会有异常的表现。

下面例子中,盒子底部和顶部的内外边距,和左右外边距有同样的大小。

1
2
3
4
5
6
7
8
9
10
11
12
<div class="box">
I have margin and padding set to 10% on all sides.
</div>

<style>
.box {
border: 5px solid darkblue;
width: 300px;
margin: 10%;
padding: 10%;
}
</style>

使用百分比作为元素外边框(margin)和填充(padding)的单位时,值是以包含块的内敛尺寸进行计算的,也就是元素的水平宽度。

min- 和 max-尺寸

可以给元素设置一个最小或最大尺寸。如果有一个包含了变化内容的盒子,至少有个确定高度,可以设置min-height属性。盒子就会一直保持大于这个最小高度,如果有比最小高度状态下所能容纳的更多内容,盒子就会变大

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="wrapper">
<div class="box"></div>
<div class="box">These boxes both have a min-height set, this box has content in it which will need more space than the assigned height, and so it grows from the minimum.</div>
</div>

<style>
.box {
border: 5px solid darkblue;
min-height: 150px;
width: 200px;
}
</style>

max-width的常见用法是,在没有足够的空间以原有宽度展示图像时,让图像缩小,同时确保他们不会比这一宽度大

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="wrapper">
<div class="box"><img src="star.png" alt="star" class="width"></div>
<div class="box"><img src="star.png" alt="star" class="max"></div>
<div class="minibox"><img src="star.png" alt="star" class="max"></div>
</div>

<style>
.box {
width: 200px;
}
.minibox {
width: 50px;
}
.width {
width: 100%;
}
.max {
max-width: 100%;
}
</style>

这可以让图片可响应,所以在更小的设备上浏览时,会合适的缩放。

视窗单位

视窗,即在浏览器中看到的部分页面,也是有尺寸的。
和视窗相关的度量单位vw(视窗宽度)、vh(视窗高度),使用这些单位,可以把一些东西做的随用户的视窗改变的大小

1vh等于视窗高度的1%

1
2
3
4
5
6
7
8
9
10
11
12
<div class="box">
A
</div>

<style>
.box {
border: 5px solid darkblue;
width: 20vw;
height: 20vh;
font-size: 10vh;
}
</style>

评论