幻影 margin/padding 在父 div 之上
Phantom margin/padding on top of parent div
这是问题的 link:link
这里的div
就是绿色里面的灰色。您会注意到它们的宽度 将 适合父级(绿色)。但是,子 div 上的 float: left
属性 什么都不做。只有在父级上添加 float: left
时才会起作用。
这样做时,它会在父 div 与导航元素的顶部添加一些虚拟间距。
.options {
margin: 0;
padding: 0;
display: block;
width: 100%;
height: 55px;
background-color: green;
/* float property */
float: left; /* this will put child divs side by side but add space on top */
}
这是因为您没有清除包含浮动元素的容器元素。一个快速的解决方案是在您的 2 个容器(.navbar-3
、.options
)上添加 overflow: hidden;
。
这样做的唯一问题是,容器元素之外的所有内容都不再可见。
另一种解决方案是通过添加以下样式来实施 .clearfix
hack:
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
* html .clearfix { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
在您的容器元素上,您现在可以添加 clearfix
class。
这是问题的 link:link
这里的div
就是绿色里面的灰色。您会注意到它们的宽度 将 适合父级(绿色)。但是,子 div 上的 float: left
属性 什么都不做。只有在父级上添加 float: left
时才会起作用。
这样做时,它会在父 div 与导航元素的顶部添加一些虚拟间距。
.options {
margin: 0;
padding: 0;
display: block;
width: 100%;
height: 55px;
background-color: green;
/* float property */
float: left; /* this will put child divs side by side but add space on top */
}
这是因为您没有清除包含浮动元素的容器元素。一个快速的解决方案是在您的 2 个容器(.navbar-3
、.options
)上添加 overflow: hidden;
。
这样做的唯一问题是,容器元素之外的所有内容都不再可见。
另一种解决方案是通过添加以下样式来实施 .clearfix
hack:
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
* html .clearfix { zoom: 1; } /* IE6 */
*:first-child+html .clearfix { zoom: 1; } /* IE7 */
在您的容器元素上,您现在可以添加 clearfix
class。