tags:

views:

52

answers:

2
<html>
 <div style="width:200px;">
  <div style="background:red;height:5px"></div>
  <div style="background:yellow">
   Magnets?
  </div>
  <div style="background:green;height:5px"></div>
 </div>
</html>

Rendering with "Magnets?" wrapped in h3 tags

How come the divs cease to be contiguous if "Magnets?" is wrapped in a paragraph or heading tag?

+2  A: 

The elements you're wrapping with likely have default margins.

great_llama
Thanks! Setting the default margins to 0 works, but why doesn't the div stretch with the content?
Terminal Frost
+1  A: 

You need to zero out the margins on the h3 or p.

<html>
 <div style="width:200px;">
  <div style="background:red;height:5px"></div>
  <div style="background:yellow">
   <h3 style="margin:0px;">Magnets?</h3>
  </div>
  <div style="background:green;height:5px"></div>
 </div>
</html>

If you want to keep the margin on the h3 and other elements then you need to fix the problem of the margins of the elements within the div collapsing. There are several ways to fix this:

  1. Add a border to the div
  2. Add a 1px border to the div
  3. Remove margin from the element and add it to the div instead.

The following link provides more info:

http://www.complexspiral.com/publications/uncollapsing-margins/

Waleed Al-Balooshi
Thanks for the response! The solution does work, however shouldn't the heading's margin push it down relative to the padding of it's parent div?
Terminal Frost
Read the following posts for more info on padding and margins: http://www.complexspiral.com/publications/uncollapsing-margins/ http://www.goer.org/HTML/intermediate/margins_and_padding/
Waleed Al-Balooshi
@Terminal The problems is with collapsing margins. Read the first link I provided in the comment above for information about this. To fix it you can either set a 1px padding on the main div or give it a border. This will allow you to keep the margin on the h3 and have the background color encompass the entire element.
Waleed Al-Balooshi