首页 > Chrome 中 div 设置 height: 100px 再设置大的 padding 高度为什么变大了?

Chrome 中 div 设置 height: 100px 再设置大的 padding 高度为什么变大了?

另外我也设置了 box-sizing: border-box, 在 Chrome 里调试的,
关于 <div> 的代码大概是:

div{
   height: 100px;
   padding: 200px 0px;
}

我想的是设置了 height 之后高度肯定要限制的, 这要怎么做?


之前表述得不清楚,修改一下答案。图来源于网上。
盒子模型有两种,分别是标准盒子模型和IE盒子模型。
当我们在网页顶部加上doctype声明的时候,浏览器会使用标准盒子模型去解释网页。
如果网页没有doctype声明的时候,ie浏览器会使用IE盒子模型去解释网页,而firefox, chrome等浏览器则仍然使用标准盒子模型区解释网页,这就出现了不兼容问题。

所以一般我们采用的是标准盒子模型。

另外width和height是可以被撑大的。


我想楼主的意思是不要让padding把box撑大吧,你可能以为height就限制了高度,但是是在盒装模型里溢出的部分会自动撑出,因为你使用的是border-box的盒装模型,height的高度就把padding包括在里面了,当padding的高度超过了height本身就会溢出而撑开,在你的例子中,最终盒装模型如下

可以看出来,本身内部的height已经到0了,但是padding还是超过了所有的height,因此整个元素就被撑大了。

我不知道你要实现什么东西,因为从你的css里来看,你要实现的效果非常矛盾。你既要padding在200px,又要高度不大于100px,那多出这么多高度干嘛呢?你干脆把你要实现什么效果的示意图画出来吧。


洗漱完毕,突然想起,这问题我貌似看错重点了,回来一看果然是。很不好意思。

变大是肯定的。我们看看w3c文档
http://www.w3.org/TR/2012/WD-css3-ui-...

border-box
The specified width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified ‘width’ and ‘height’ properties. As the content width and height cannot be negative ([CSS21], section 10.2), this computation is floored at 0.
content的高宽的是用定义的width和height减去border和padding。但是content的width和height不能为负,最小差为0。如不满足条件会增大 “border box” 让差值最小0。

以上足够解释你的标题中的疑虑,至于你文中问的要怎么做。从你提供的例子看就是矛盾的问题。最好的方法就是遵循规范,避开问题。

以下是一开始的回复,我也就不删了。
----------------------------------------------------------------------------------------------------------------------------------
其实这个问题搜搜就有了。这要看你的chrome版本。比如我们看w3cschools给的 CSS3 Browser Support Reference
http://www.w3schools.com/cssref/css3_...

从chrome9开始支持 box-sizing 标准,而不需要 -webkit-box-sizing

所以你看看chrome版本,如果<9 就需要 -webkit-box-sizing:border-box;

如果版本>=9,那就要考虑是不是写错了。

我也给个例子

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta http-equiv="content-type" content="text/html;charset=utf-8" />
	<style type = "text/css">
        *{
            margin:0px;
            padding:0px;
        }
        #_border_box{
            width:200px;
            height:200px;
            line-height:20px;
            border:10px ridge #f60;
            padding:100px;
            -moz-box-sizing:border-box;
            -webkit-box-sizing:border-box;
            box-sizing:border-box
        }
	</style>
</head>
<body>
       <div id="_border_box">200px</div>
</body>
</html>
【热门文章】
【热门文章】