Reputation: 424
Currently, one div is floated - my question is why are two divs overlapping even if the dimensions are set in every one of them? How can I fix this?
HTML:
<div class="wrapper">
<div class="block1">
</div>
<div class="block2">
</div>
</div>
My CSS:
.wrapper {border:black solid;width:500px;height:1000px}
.block1 {width:300px;height:300px;float:right;border:solid red;}
.block2 {width:300px;height:300px;border:solid green;}
jsfiddle here - http://jsfiddle.net/FLwUA/1/
Upvotes: 3
Views: 10520
Reputation: 709
The two divs overlap because one is fixed in the DOM layout (the non floated one) and the other is effectively removed from the DOM structure (the floated one) and is free to overlay as the two will not fit side by side in the parent container due to the width being two small.
To fix this there are several options, depending what you mean by fix.
You can use the CSS 'clear' attribute on the non floated div to force it to have nothing on one or both sides of it ('clear:both;' or 'clear:left;' in the scenario given).
or
You can set the non-floated div to be floated, which will also take it out of the DOM layout so that it is now in the same situation as the other floated div.
Additional
Just for information in case all the floating objects become an issue. One way to achieve the same result without floating the divs is to use the "display:inline-block;" CSS attribute on both of them, but you would need to swap the ordering of the two divs around in the HTML to get the same layout.
Upvotes: 5
Reputation: 68586
It's because you are giving them defined widths using pixels - your wrapper width is only 500px
, however you are using 300px
by 300px
divs inside which is equal to 600px
so it'll end up outside the container div. You could use percentages in relation to the parent div like so. Here's a jsFiddle.
.wrapper {border:black solid; width:500px;height:1000px}
.block1 {width:49%;height:300px;float:right;border:solid red;}
.block2 {width:49%;height:300px;border:solid green;}
Alternately, if you want to keep the fixed width and have one over the other if they are too large, you could just use float
on the second block. Here is the jsFiddle.
.wrapper {border:black solid; width:500px;height:1000px}
.block1 {width:300px;height:300px;float:right;border:solid red;}
.block2 {width:300px;height:300px;float:left; border:solid green;}
Upvotes: 3