Background not showing behind floating divs [duplicate]
what's wrong with this code?
The background disappears behind the divs when I add float: left
to #text
and #text2
. But when I remove the float: left
, everything looks good.
<!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>
You container div #right_b
is collapsing because its children are floating. You can fix this with the "Clear-Fix" technique. You may want to check out the following Stack Overflow post for a few solutions:
- Which method of ‘clearfix’ is best?
One popular solution is to add overflow: hidden
to your container div: #right_b
:
#right_b {
background:transparent url('img/right.png');
background-position: right top;
background-repeat: repeat-y;
overflow: hidden;
}
Another common one is to add a <div style="clear: both;"> </div>
before closing your container 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>
I think you have to give #right_b
also a minimal height:
#right_b{
background:transparent url('img/right.png');
background-position: right top;
background-repeat: repeat-y;
min-height: 30px;
}
Float elements are took out of the normal document flow, so if an element does not contain other "normal" elements, this element has a height of 0
(as it has no content).
Add this to your stylesheet:
.group:before,
.group:after {
content:"";
display:table;
}
.group:after {
clear:both;
}
.group {
zoom:1; /* For IE 6/7 (trigger hasLayout) */
}
And add the class "group" to your "right_b" element, this will fix the collapsing div:
<div id = "right_b" class="group">
<div id = "text">text 1</div>
<div id = "text2">text 2</div>
</div>
精彩评论