Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what causes the margin top to not show?

Tags:

html

css

why the margin-top: 20px; in footer doesn't work? what's the reason may be cause to this?

#main {
  margin: 0 auto;
  width: 960px;
}

#left {
  float: left;
  border: 1px solid red;
  width: 300px;
  margin-right: 10px;
  height: 500px;
}

#right {
  float: right;
  border: 1px solid green;
  width: 500px;
  height: 500px;
}

#footer {
  clear: both;
  margin-top: 20px;
  border: 1px solid lime;
  height: 200px;
}
<div id="main">
  <div id="left"></div>
  <div id="right"></div>
  <div id="footer"></div>
</div>
like image 704
zhuanzhou Avatar asked Jul 09 '11 03:07

zhuanzhou


2 Answers

Try to add some clearer:

<div id="main">
  <div id="left"></div>
  <div id="right"></div>
  <div style="clear:both"></div>
  <div id="footer"></div>
</div>

When an element's css clear set to both, it won't let ANY FLOATING element to overlap in its border and text area, meaning margin can be overlapped by float elements. That is why you cannot see your footer's margin. So we basically need an extra div, which is not floated, so the margin of your footer has something to push. Try my codes below (with BG and Borders), you'll see what I'm saying.

Without extra div:

<div id="main">
  <div id="left" style="background:#FF000;border:solid 1px #000000;float:left">LEFT</div>
  <div id="right" style="background:#00FF00;border:solid 1px #000000;float:right">RIGHT</div>
  <div id="footer" style="clear:both;margin-top:10px;background:#00FFFF;border:solid 1px #000000;">FOOTER</div>
</div>

With extra div:

<div id="main">
  <div id="left" style="background:#FF000;border:solid 1px #000000;float:left">LEFT</div>
  <div id="right" style="background:#00FF00;border:solid 1px #000000;float:right">RIGHT</div>
  <div style="background:#0000FF;border:solid 1px #000000;clear:both">CLEARER</div>
  <div id="footer" style="margin-top:10px;background:#00FFFF;border:solid 1px #000000;">FOOTER</div>
</div>

Resource:

http://www.w3.org/TR/CSS2/visuren.html#flow-control

like image 134
dpp Avatar answered Sep 27 '22 21:09

dpp


Add a div to clear the floating items

<div id="main">
  <div id="left"></div>
  <div id="right"></div>
  <div class="clear"></div>
<div id="footer"></div>
</div>

and the css

.clear {
   clear: both;
}

since the left and right where floating, the space they occupied collapsed, so clearing the float brings back this space and the footer will appear right after it

like image 36
Ibu Avatar answered Sep 27 '22 22:09

Ibu