日期:2014-05-17  浏览次数:20606 次

float对块有什么影响
两个div是一样的,div2加上float:right;后下面多出20px,怎么回事呢?


HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Fixed Width Rounded Corner Box</title>
<style type="text/css">
<!--
/* pretty stuff
================================== */
body {
  font: 62.5%/1.6 "Gill Sans", Futura, "Lucida Grande", Geneva, sans-serif;
  color: #666;
  background: #fff;
  
}

h2 {
  font-size: 2.2em;
  font-weight: normal;
  line-height: 1;
  color: #94b767;
  margin: 0;
}

.box {
  font-size: 2em;
}
.box2 {
  font-size: 2em;
}

/* rounded corner box
================================== */

.box {
  width: 418px;
  background: #effce7 url(images/bottom.gif) no-repeat  left bottom;
}

.box h2 {
  background: url(images/top.gif) no-repeat left top;
}

.box h2 {
  padding: 10px 20px 0 20px;
}

.box p {
  padding: 0 20px 10px 20px;
}
/*================================== */

.box2 {

    float:right;            /* 脱离文档流,究竟发生了什么事 */
    
/*    position:absolute;
    left:500px;    */
    
    width: 418px;
    background: #effce7 url(images/bottom.gif) no-repeat  left bottom;
}

.box2 h2 {
    background: url(images/top.gif) no-repeat left top;
}

.box2 h2 {
    padding: 10px 20px 0 20px;
}

.box2 p {

    padding: 0 20px 10px 20px;
}

-->
</style>
</head>

<body>

<div class="box2">
  <h2>Lorem Ipsum2</h2>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin venenatis turpis ut quam. In dolor. Nam ultrices nisl sollicitudin sapien. Ut lacinia aliquet ante.</p>
</div>

<div class="box">
  <h2>Lorem Ipsum</h2>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin venenatis turpis ut quam. In dolor. Nam ultrices nisl sollicitudin sapien. Ut lacinia aliquet ante.</p>
</div>

</body>
</html>



------解决方案--------------------
设置* {
margin:0;
padding:0;
}---zheshi 这是习惯
------解决方案--------------------
p有默认的margin.
没有float之前,没有看到p和div之前的margin-bottom, 是因为margin的自动合并. 
通过firebug,可以看到其实这个margin是在的,只是没有体现在p和div之前而已.

可以看一下这里的介绍:http://www.w3.org/TR/CSS2/box.html#margin-properties
http://www.w3school.com.cn/css/css_margin_collapsing.asp

一起学习一下~