I apologize if this topic has been covered in another thread. I wasn't able to find an answer to my specific question in other threads, and so any help is appreciated. Here is what is causing me headaches: CSS #box1 { width: 500px; height: 500px; background: silver; margin: 0 auto; } h1{ margin-top: 100px; } Code (markup): HTML <div id="box3"> <h2>Test Text</h1> </div> Code (markup): The problem is that I am trying to move the h1 tag down 100px using margins instead of positioning it. What is happening is that when I give the h1 element a margin-top property of 100px that it moves the entire containing block down 100px rather than just the h1 tag within the box. I have noticed that this can be remedied by giving the box a border or setting the position of the box to either absolute or fixed. But what I am wanting to know is why this is happening. I know that I can use positioning instead of margins, but I am just wanting to know the principle behind this, and what possible solutions to avoid it while still being able to use margins.
Doctype is important and another elements - You hidden rest of code. I see any mistake here: <h2>Test Text</h1> Code (markup): You want test h2 or h1 ?
Thanks for your reply, <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> I apologize for a few typos on my part. The correct code is below: CSS: #box1 { width: 500px; height: 500px; background: silver; margin: 0 auto; } h1{ margin-top: 100px; } Code (markup): HTML: <div id="box1"> <h1>Test Text</h1> </div> Code (markup):
I was able to find a solution to my problem. The problem had to do with collapsing margins and nested margins. I simply separated touching margins with 1px padding in the parent container and that was enough to separate the two margins. This also explains why adding the border worked. Thanks for the help.
This is why I avoid using margin on the horizontal as much as possible - and why instead of margin-top on the h1 I'd be putting padding-top on #box1 - then you only need one declaration, not two. Positive margins should be used sparingly IMHO for just this reason. (hell, negative margins are more predictable than positive)