div等元素height:100%高度为什么不生效

来源:互联网 发布:电脑软件打不开怎么办 编辑:程序博客网 时间:2024/06/15 09:04

以前一直很郁闷一个问题,为什么设置height:100%不生效,尤其是设置body:height:100%不生效,后来就很少使用了这个了。

今天在学习谷歌地图时关于height:100%看到了解答:

In specific, all percentage-based sizes must inherit from parent block elements, and if any of those ancestors fail to specify a size, they are assumed to be sized at 0 x 0 pixels

具体地讲,所有基于本分比的尺寸必须从父块元素继承,并且如果任一父项未能指定尺寸,则它们的尺寸假定为0 x 0像素

所以我特地有查看了我只设置body的height:100%的情况,发现body的高度就为0,所以子元素的高度设置为height:100%也为0,如下
这里写图片描述

这里写图片描述

那原因是因为body设置的height:100%要从它的父块元素那里继承,但它的父块元素html没有设置高度,查看html的height:

这里写图片描述

当我再html设置了height:100%后,body和div设置的height:100%便生效了

body的height:100%有作用了:

这里写图片描述

div的height:100%有作用了:
这里写图片描述

当然html也有高度了:
这里写图片描述

可以测试本例子的完整代码:

<!DOCTYPE html><html>    <head>        <title></title>        <style type="text/css">            html,body { height: 100%;margin: 0; padding: 0;}            #map { height: 100%; }        </style>        <script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>         </head>    <body>        <div id="map"></div>        <script type="text/javascript">            var map ;            function initMap(){                map = new google.maps.Map(document.getElementById('map'),{                    center: {lat: -34.397, lng: 150.644},                    zoom: 8                });            }            initMap();        </script>    </body></html>
通过谷歌地图的学习明白了为什么之前设置的height:100%不生效,尤其是body也设置了height:100%,但一直没去想它的父元素height没设置高度,导致高度为0.因为父元素没高度,父元素的父元素也没高度,要同时将body和html都设置高度