使用margin/padding的百分比值来解决自适应高度的关键在于:容器margin/padding的百分比参照物是父元素的宽度,而容器的width的百分比参照物也是父元素的宽度,俩属性参照物一致,那么想要把这俩属性的值统一起来就简单了。
margin
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style type="text/css">
*{margin: 0;padding: 0;}
body,html{width: 100%;height:100%;}
#box{height: 100%;width: 100%;background: #ccc;}
.marg{width: 40%;margin-bottom: 40%;position: relative;margin-left: 20px;float: left;}
.mar_ch{background: blue;position: absolute;top: 0;left: 0;width: 100%;padding-bottom: 100%;}
</style>
<body>
<div id="box">
<div class="marg">
<div class="mar_ch"></div>
</div>
<div class="marg">
<div class="mar_ch"></div>
</div>
</div>
</body>
</html>
padding ————推荐使用padding
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style type="text/css">
*{margin: 0;padding: 0;}
body,html{width: 100%;height:100%;}
#box{height: 100%;width: 100%;background: #ccc;}
.pad{width: 40%;padding-bottom: 40%;margin-left: 20px;float: left;background: #000;}
</style>
<body>
<div id="box">
<div class="pad">
</div>
<div class="pad">
</div>
</div>
</body>
</html>