I'm having a very frustrating situation with margins.. I have a div in the top of my markup that is floated to the right.
.grey{
float:right;
width:200px;
}
I need to apply some styles (background and margin) to the first paragraph after.
.blue{
background-color: blue;
margin: 10px;
overflow:hidden;
}
Now I have to make the paragraph "overflow: hidden" so the background doesn't extend under the floated div, but I have 2 strange problems.
the margin doesn't seem to apply to the side of the paragraph that touches the float;
the margin seems to apply to the floated element beside it..
Here's a fiddle. http://jsfiddle.net/whiteatom/Nkfzg/6/
Could anyone tell me how to get the margin space between the "Blue" element and the floated one? and could anyone tell me how to make my floated element not have these phantom margins?
Cheers,
whiteatom
You need to apply a left margin to the floating element in order to space it away from the paragraph:
.grey {
float: right;
width: 200px;
margin-left: 10px;
}
As mentioned, margin collapse causes the top margin of your paragraph to affect the page body instead. This causes it to push both the paragraph and the floating element down.
To remove the top margin from the floating element, you have two options (choose only one):
Cancel margin collapse by floating the body:
body {
float: left;
}
This causes the margin to affect only the paragraph. Updated fiddle
Apply a negative top margin to your floating element:
.grey {
float: right;
width: 200px;
margin-left: 10px;
margin-top: -10px;
}
Here, you're shifting the floating element up to counter the margin collapse, which remains in effect. Updated fiddle