I’m working on a project, but I’ve been stuck trying to figure out a styling issue for a few hours now. The problem is, it appears to be terrifyingly simple.
I have simplified the problem down to two divs. Both identical, each with a margin of 5px (all sides). In every single browser, this renders with only 5px in between the two divs. It essentially ignores one of the margins completely.
In other words, I am having problems with the top and bottom margins.
Here’s an simple example which illustrates my point.
<html>
<head>
<style type="text/css">
p { background-color:yellow; }
p.margin {
margin-top:100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;
}
div { background: #CCC; }
</style>
</head>
<body>
<p>This is a paragraph with no specified margins.</p>
<div>
<p class="margin">This is a paragraph with specified margins.</p>
</div>
</body>
</html>
For some reason, the #CCC background does not extend to the limits of the margin on top and bottom.
-HOWEVER-
What’s even stranger, is that when you add a border to the div, say:
border: 1px solid #FF0000;
The entire thing corrects itself and displays correctly.
I’d greatly appreciate it if somebody could explain to my why this problem is occurring.
@donboe, I just posted a screenshot, but it says “Pending approval”.
@kalon, I understand the box model, but my computer does not seem to be rendering the margins correctly.
<html>
<head></head>
<body style="margin: 0;">
<div style="margin: 5px;">
Text 1
</div>
<div style="margin: 5px;">
Text 2
</div>
</body>
There should be 10px in between the two divs (so I understand) but my computer renders only 5px. The margins of each div seem to overlap eachother.
EDIT***
To clarify, my problem is about margins rendering incorrectly. The problem in the project I am working on is that 10px gets reduced to 5px. The code I posted originally is simply an example of what causes the margins to be rendered incorrectly on my computer.
I could understand this if there would be a parent holding these two divs using a top/bottom margin as well. Because than you experience collapsing margins. As a tryout, try to give both divs a top-border of 1 px or top-padding of 1 px;
Off Topic:
You should not use inline styles; <div style=“margin: 5px;”>. Use CSS instead:
Well I just read about collapsing margins, and they are definitely the problem I am experiencing. I didn’t even know margins did that. Well I guess I’ll have to find a workaround for that. Thanks for all your help guys.
EDIT*** I was wondering why this problem of collapsing margins wasn’t occurring in one of my other documents. The difference was that those divs were floating and apparently floating objects never have collapsed margins.