三种解法:
css3弹性盒子(Flex Box)解法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
<title>Title</title>
<style>
.box {
width:200px;
height:300px;
background:red;
display:flex;
display: -webkit-flex;
flex-direction:column;
-webkit-flex-direction:row;}
.a {height:100px;background:green;}
.b {background:blue;flex:1}
</style>
</head>
<body>
<div class="box">
<div class="a">
</div>
<div class="b">
</div>
</div>
</body>
</html>
CSS3 弹性盒( Flexible Box 或 flexbox),是一种当页面需要适应不同的屏幕大小以及设备类型时确保元素拥有恰当的行为的布局方式。
引入弹性盒布局模型的目的是提供一种更加有效的方式来对一个容器中的子元素进行排列、对齐和分配空白空间。
display:flex或display:inline-flex:指定父元素为弹性盒子;
flex-direction:指定flex子项在flex父元素中的排列方式。
flex-direction属性取值:
- row:主轴与行内轴方向作为默认的书写模式。即横向从左到右排列(左对齐)。
- row-reverse:对齐方式与row相反。
- column:主轴与块轴方向作为默认的书写模式。即纵向从上往下排列(顶对齐)。
- column-reverse:对齐方式与column相反。
纯css解法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
<title>Title</title>
<style>
body { height: 100%; padding: 0; margin: 0; }
.box { height: 400px; position: relative; }
.a { height: 100px; background: #ff0000; }
.b { background: #00ff00; width: 100%; position: absolute; top: 100px ; left: 0 ; bottom: 0;}
</style>
</head>
<body>
<div class="box">
<div class="a"></div>
<div class="b"></div>
</div>
</body>
</html>
*外容器:position:relative。高度固定为100px的盒子使用相对定位,高度要求自适应的盒子使用绝对定位,再设定它的top:100px;left:0;bottom:0;
js解法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="gb2312">
<title>Title</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<style>
body { height: 100%; padding: 0; margin: 0; }
#box { height: 400px; position: relative; }
#a { height: 100px; background: #ff0000; }
#b { background: #00ff00; width: 100%; }
</style>
</head>
<body>
<div id="box">
<div id="a"></div>
<div id="b"></div>
</div>
</body>
<script language="javascript" >
$(document).ready(function() {
var h1 = $("#box").height();
var h2 = $("#a").height();
var h3 = h1-h2;
$("#b").css("height",h3);
})
</script>
</html>
获取外层盒子和固定高度盒子的高度值,将其相减,结果就是自适应盒子的高度。