参见英文答案 >
css background color with floating elements4个
这段代码有什么问题?
这段代码有什么问题?
当我添加float:left到#text和#text2时,背景消失在div后面.但当我移除浮子时:左,一切看起来都不错.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style type="text/css"> #first{ width: 200px; background-color: #345752; } #left_b{ background:transparent url('img/left.png'); background-position: left top; background-repeat: repeat-y; min-height: 30px; } #right_b{ background:transparent url('img/right.png'); background-position: right top; background-repeat: repeat-y; } #text{ float: left; width: 50px; height: 30px; } #text2{ float: left; width: 70px; height: 30px; } </style> </head> <body> <div id = "first"> <div id = "left_b"> <div id = "right_b"> <div id = "text">text 1</div> <div id = "text2">text 2</div> </div> </div> </div> </body> </html>
解决方法
容器div #right_b正在折叠,因为它的子节点是浮动的.您可以使用“Clear-Fix”技术解决此问题.您可能需要查看以下Stack Overflow帖子以获取一些解决方案:
> Which method of ‘clearfix’ is best?
一个流行的解决方案是添加overflow:hidden到你的容器div:#right_b:
#right_b { background:transparent url('img/right.png'); background-position: right top; background-repeat: repeat-y; overflow: hidden; }
另一个常见的是添加< div style =“clear:both;”>& nbsp;< / div>在关闭容器div之前:
<div id="first"> <div id="left_b"> <div id="right_b"> <div id="text">text 1</div> <div id="text2">text 2</div> <div style="clear: both;"> </div> </div> </div> </div>