Reputation: 16895
I have the following code:
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<style type="text/css">
.mydiv {
width:300px;float:left;background-color:#ff0000;height:250px;margin-right:10px
}
</style>
</head>
<body>
<div style="margin-left:auto;margin-right:auto;width:1000px;clear:both">
<div style="margin-right:auto;margin-left:auto;text-align:center;margin-top:5px;">This is the title</div>
</div>
<div style="margin-right:auto;margin-left:auto;clear:both;width:1000px;margin-top:10px">
<div class="mydiv">Div</div>
<div class="mydiv">Div</div>
<div class="mydiv">Div</div>
</div>
</body>
</html>
The problem is that the second and the third divs do not align properly (horizontally) with the first. For some reasons, a vertical offset makes the second and the third div appear a little lower than the first. Why is this?
Thankyou
I am using Chrome 25, on MacOS X. Hope it helps somehow.
Upvotes: 1
Views: 2918
Reputation: 59859
Its because you have clear: both;
on the parent container of the three red boxes, if you remove that property all three will be aligned as expected.
You need to include the clear property after the last floated closing </div>
or you can use a clearfix which uses the ::after
pseudo-element on the container to clear floated elements within it.
You can see the container now respects the floated red boxes ..
Upvotes: 2
Reputation: 39990
Randomly poking around tells me the way to fix the offset is to remove the clear: both;
declaration from the parent <div>
of the three float
ed <div>
s:
<div style="width: 1000px">
<div style="…">Div</div>
<div style="…">Div</div>
<div style="…">Div</div>
</div>
To make the parent <div>
"wrap around" the float
ed <div>
s, you need to add a clear
ed <div>
after the float
ed ones:
<div style="width: 1000px">
<div style="…">Div</div>
<div style="…">Div</div>
<div style="…">Div</div>
<div style="clear: both;" />
</div>
You can also use a "clearfix" (for instance the one from HTML 5 Boilerplate on the containing <div>
instead:
<div class="clearfix" style="width: 1000px">
<div style="…">Div</div>
<div style="…">Div</div>
<div style="…">Div</div>
</div>
Upvotes: 1