2013-04-10 63 views
1

我最近遇到了一个问题,我似乎与css中的box-sizing:border-box标记有非常不一致的行为。例如,下面的代码块似乎完全忽略了标签。框大小和高度预期行为

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.one { 
margin-bottom:30px; 
-webkit-box-sizing: border-box; 
-moz-box-sizing: border-box; 
box-sizing: border-box; 
margin-left:10px; 
overflow:hidden; 
background-color:green; 
width:40px; 
height:40px; 
} 
.two { 
height:30px; 
width:30px; 
background-color:black; 
} 
</style> 
</head> 
<body> 
<div class = 'two'></div> 
<div class = 'one'></div> 
<div class = 'two'></div> 
</body> 
</html> 

我要承担这是预期的行为,但我还没有看到明确讲实例,其中箱尺寸是行不通的任何物品,并通过实验我一直无法找到什么CSS属性似乎影响它,除了基于像素的宽度/高度似乎与它发挥不佳。任何人都愿意澄清,这是一种只适用于百分比还是仅适用于水平的房产?

+0

预期的行为是什么? http://tinker.io/00be0 – cimmanon 2013-04-10 18:27:58

+1

你的元素没有边框或填充。我不明白为什么'box-sizing:border-box'会改变任何东西。 – BoltClock 2013-04-10 18:30:42

+0

保证金不是盒子模型的一部分。这解释了很多。 我假设实现类似行为的正确过程将嵌套在使用填充的父div中的内容。感谢您的回答,我应该早点解决这个问题。 – danShumway 2013-04-10 19:08:42

回答

1

我不确定你明白box-sizing:border-box应该做什么。那段代码会忽略标签?请解释你期望的行为以及这种差异。

至于物业本身,我假设你已经做了一些四处看看,你熟悉box-model

例如,使用“正常”盒模型将添加填充到外侧的元件的添加填充到一个元素,但是,使用相同的填充有box-sizing:border-box将增加内部的填充到该元素将保留您的原始大小。

这可以在以下jsFiddle中说明。

<style> 
.one { 
-webkit-box-sizing: border-box; 
-moz-box-sizing: border-box; 
box-sizing: border-box; 
width:50px; 
height:50px; 
padding:10px; 
background-color:#3e3e3e; 
} 

.two { 
width:50px; 
height:50px; 
padding:10px; 
background-color:red; 
} 

<div class = "one">one1</div><div class = "one">one2</div><div class = "one">one3</div> 
<div class = "two">two1</div><div class = "two">two2</div><div class = "two">two3</div> 

这种情况造成的需要,以确保你的数学是正确的或风险不使用边界框属性时,破坏你的造型。举例来说,如果你有<div>原来决心分别跨越你的页面的三分之一,您可以设置它是这样的:

<style> 
.one { 
    width:33%; 
    background-color:#3e3e3e; 
    float:left; 
} 
</style> 

<div class = "one">one1</div> 
<div class = "one">one2</div> 
<div class = "one">one3</div> 

http://jsfiddle.net/b4LNp/

这是好的,但添加填充它没有border-box会导致div的总大小等于大于33%(在这种情况下,宽度+ 1em填充33%)。这会破坏您创建的列,因为它们现在太宽而不能彼此并排。

<style> 
.one { 
    width:33%; 
    background-color:#3e3e3e; 
    float:left; 
    padding:1em; 
} 
</style> 

<div class = "one">one1</div> 
<div class = "one">one2</div> 
<div class = "one">one3</div> 

http://jsfiddle.net/u4w5B/

使用border-box反而把填充在元件的内侧,保持每个在它的33%,并确保不管你怎么空间的元素,他们将留在宽度你最初告诉它。这消除了大量额外的,不必要的数学的需要。

<style> 
.one { 
    width:33%; 
    background-color:#3e3e3e; 
    float:left; 
    padding:1em; 
    -webkit-box-sizing: border-box; 
    -moz-box-sizing: border-box; 
    box-sizing: border-box; 
} 
</style> 

<div class = "one">one1</div> 
<div class = "one">one2</div> 
<div class = "one">one3</div> 

http://jsfiddle.net/u4w5B/1/

欲了解更多信息,请查看以下链接:

w3 box-model explanation

Paul Irish's suggestion for *{box-sizing:border-box}

CSS Tricks box-sizing

Hong Kiat box-sizing in CSS3

希望有帮助!

+0

只是我很愚蠢,错过了保证金和填充/边框之间的区别。 – danShumway 2013-04-10 19:13:55

相关问题