This question already has an answer here:
这个问题在这里已有答案:
- CSS: Adding a border changes the background-color (?!) 4 answers
CSS:添加边框会更改背景颜色(?!)4个答案
This isn't a production issue this is just something I ran across and have been wondering about. The margin of an inside div won't get the parent div's background color, unless I add a border to the parent div. So the innerDiv's margin won't get the background of the header div unless I add a border to the header div.
这不是一个生产问题,这只是我遇到的事情并且一直在想。内部div的边距不会获得父div的背景颜色,除非我向父div添加边框。因此,除非我向标题div添加边框,否则innerDiv的边距将不会获得标题div的背景。
<div id="container">
<div id="header">
<div id="innerDiv">Title</div>
</div>
<div id="content" >
<button>Remove Border</button>
</div>
<div id="footer" >
footer
</div>
</div>
this fiddle hopefully demonstrates my question. http://jsfiddle.net/eTq2P/6/
这个小提琴有希望证明我的问题。 http://jsfiddle.net/eTq2P/6/
So I'm not looking for a work around, I'm wondering why the margin doesn't get the background color of the parent div unless a border is added to the parent div. I was expecting the margin to be included inside of the parent div.
所以我不是在找工作,我想知道为什么边距不会得到父div的背景颜色,除非边框被添加到父div。我期待保证金包含在父div中。
2 个解决方案
#1
3
Adding border forces #header to contain #innerDiv, therefore stretching it to the size if #innerDiv. You can accomplish the same thing without border by adding
添加边界力#header以包含#innerDiv,因此如果#innerDiv将其拉伸到大小。你可以通过添加来完成没有边框的相同的事情
#header {overflow: auto;}
See also: CSS: Adding a border changes the background-color (?!)
另请参阅:CSS:添加边框会更改背景颜色(?!)
#2
0
*{box-sizing:border-box;} helps a lot.
* {box-sizing:border-box;}有很多帮助。
#1
3
Adding border forces #header to contain #innerDiv, therefore stretching it to the size if #innerDiv. You can accomplish the same thing without border by adding
添加边界力#header以包含#innerDiv,因此如果#innerDiv将其拉伸到大小。你可以通过添加来完成没有边框的相同的事情
#header {overflow: auto;}
See also: CSS: Adding a border changes the background-color (?!)
另请参阅:CSS:添加边框会更改背景颜色(?!)
#2
0
*{box-sizing:border-box;} helps a lot.
* {box-sizing:border-box;}有很多帮助。