问题是div与.parent班级的位置.这是不是在窗口顶部,但低于100像素,这是完全价值margin-bottom的.child.
谁能解释一下这里发生了什么?
这是我的HTML文档:
<html>
<head>
<style>
.parent {
}
.child {
margin-bottom:100px;
}
button {
float:left;
height:30px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
<button>click me!</button>
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是由于浮动处理不彻底以及没有掌握 Margin Collapseing造成的
空块上的边距折叠
如果没有边框、填充、内联内容、高度或最小高度来分隔块的上边距和下边距,则其顶部和底部边距会折叠。
您需要在父级overflow:auto;上使用或
通过清除浮动来消除浮动元素问题,即:使用类:
.clear:before,
.clear:after{
content: " ";
display: table;
}
.clear:after{
clear: both;
}
Run Code Online (Sandbox Code Playgroud)
注意:使用背景颜色将帮助您将来解决此类问题:
“父母没有可见的背景颜色?” 99%是浮动问题!
.clear:before,
.clear:after{
content: " ";
display: table;
}
.clear:after{
clear: both;
}
Run Code Online (Sandbox Code Playgroud)
.parent {
background: red;
}
.child {
background: gold;
margin-bottom:100px;
}
button {
float:left;
height:30px;
}Run Code Online (Sandbox Code Playgroud)
我们有折叠边距,因为.child 没有(非浮动)内容或任何要height添加到其框模型的设置,因此button折叠到最近的可用空间 - 向左浮动。
只需添加height: 1px;或仅在其中添加一个文本字符,.child您就会看到崩溃的问题“已修复”。
在父级上使用 our .clear(或):overflow:auto;
<div class="parent">
<div class="child">
<button>Left floated Button</button>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
.parent {
background: red;
}
.child {
background: gold;
margin-bottom:100px;
}
button {
float:left;
height:30px;
}
.clear:before,
.clear:after{
content: " ";
display: table;
}
.clear:after{
clear: both;
}Run Code Online (Sandbox Code Playgroud)
您可以看到,.parent由于.clear黑客为.child和 浮动按钮创建了一个包装,所以添加了上下文/内容。Parent现在只知道.child100px 边距导致.child仍然存在边距折叠问题。
仍然没有可见的child's金色背景?= 我们也需要应用.clear(或再次溢出)它!
<div class="parent clear">
<div class="child">
<button>Left floated Button</button>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
.parent {
background: red;
}
.child {
background: gold;
margin-bottom:100px;
}
button {
float:left;
height:30px;
}
.clear:before,
.clear:after{
content: " ";
display: table;
}
.clear:after{
clear: both;
}Run Code Online (Sandbox Code Playgroud)
因此,回顾一下发生的事情:
.parent空。.childfloat.child是唯一添加一些 100px 空间的元素,并将margin-bottom浮动元素推到该空间下方(因为浮动),导致空块上的边距折叠height会.child看到浮动元素在新的可用空间和未折叠边距后跳到正确的位置(在子元素的顶部) 。| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |