HTML+CSS实现标题固定高度,剩余内容物填充整个容器

这里用到的技巧为设置父元素的padding-top为标题高度,然后将标题设为浮动,position:absolute,这样可以很好地解决如下问题:

  • 页面布局需要使内容物填满整个容器,而其中一个的高度不能设置百分比
  • echarts中经常会有标题+图标容器充满整个父元素的,这里就可以为图表容器设置宽高

话不多说,实践代码走起:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<head>
<title>test fluid content</title>
<style type="text/css">
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}
html,body{
height: 100%;
width: 100%;
}
body{
position: relative;
padding-top: 30px;
}
.header{
position: absolute;
height: 30px;
width: 100%;
top: 0;
background-color: #ffaaaa;
}
.content{
height: 100%;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="content"></div>
</body>
</html>

代码分解:

页面分为(body(div.header),(div.content))这样的结构
首先将body设置一个padding-top为30的上边距,然后设置为相对定位,
子元素.header为绝对定位,根据父元素body的top为0;
子元素.content高度为100%,这里用到一个box-sizing:border-box的特性:内边距是相对于内容物之外来计算的,因此它的100%,其实是body元素除去30px的上边距之后计算得到的值。

来看一下效果吧!

enter description here

enter description here

enter description here

为了更加明显,我们将header隐藏掉:

enter description here

可以看出来,其实header相当于是一层额外的纸贴在body上哦,而body也给它留出了30px的空白位置。

这种布局主要依赖于box-sizing:border-box属性