日期:2014-05-17  浏览次数:20757 次

CSS-加了边框的子元素高度为100%时为何撑破了父容器?
上例子:
HTML code

<html>
<head>
<style type="text/css">
    #container {
        position: absolute;
        top: 50px;
        left: 50px;
        width: 600px;
        height: 500px;
        border: 5px solid black;
        background: white;
    }
    
    #child {
        float: left;
        width: 200px;
        height: 100%;
        border: 5px solid red;
        background: green;
    }
</style>
</head>

<body>
<div id="container">
<div id="child"></div>
</div>
</body>
</html>


我的理解当子元素的高度设为100%时,不论是否加边框都不应该超出父容器的高度,但现在不是这样,和解?
如果css定义元素高度不包括边框的话,如何通过css解决这个问题?注意是不用js而纯用css解决哦。

------解决方案--------------------
设置 child height 100% 时 它的height就是500px,但是border-top:5px 已经占了5px,而还有border-bottom 5px,所以会超出。


js获取 css中定义的值,需要“计算”一下。比如

HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>
        <style>
        </style>
    </head>
    <body>
        <button id="btn">弹出层</button>
        <script>
            function $(o){return document.getElementById(o)}
            
            var css = function(obj, attr, value){
                switch(arguments.length){
                    case 2:
                        //二个参数, 如果第二个参数是对象, 批量设置属性
                        if(typeof attr == 'object'){ 
                            for(var i in attr){
                                obj.style[i] = attr[i];
                            }
                        }
                        //二个参数, 如果第二个参数是字符串, 读取属性值
                        else{
                            return obj.currentStyle? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr];
                        }
                        break;
                    case 3:
                        //三个参数, 单一设置属性
                        obj.style[attr] = value;
                        break;
                    default:
                        alert('参数有误!');
                }
            }
            var o = $('btn');
            
            alert( css(o, 'fontSize') )
            
            css(o, {
                fontSize: 123+'px',
                color: 'red'
            })
            
        </script>
    </body>
</html>