float详解 先上一个简单示例,了解一下float的使用 float 属性的本质理解  float 实现页面布局

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>fl0at</title>
<style type="text/css">
#Content{
    height:600px;   
    margin-top:20px;
    background:#90C;
    
}
</style>
</head>
 
<body>
    <div id="Content">
        <div style="float:left;height:400px; background:#f00;">Content-Left</div>
        <div style="           height:400px; background:#fff;">Content-Main</div>
        <div style="clear:both;"></div>
        <div style="float:left;height: 50px; background-color: red;">左浮动</div>  
        <div style="           height:50px;  background-color: blue;">">右浮动</div>         
    </div>
</body>
</html>
View Code

float详解
先上一个简单示例,了解一下float的使用
float 属性的本质理解
 float 实现页面布局

 在Content-Main 和右浮动对应div里加上float:left或者给他们设置width如图:

float详解
先上一个简单示例,了解一下float的使用
float 属性的本质理解
 float 实现页面布局

float 属性的本质理解

      float 出现的根本意义只是用来让文字环绕图片而已。而我们目前用 float 实现页面布局本不是 float 该干的事情。

      float 属性(无论是左浮动还是右浮动)某种意义上而言与 display:inline-block 属性的作用是一模一样的,所以类似于 display:block; float:left; 的CSS代码超过95%的情况是没有道理的( display:block 是多余的)。然而,float无法等同于 display:inline-block,其中原因之一就是浮动的方向性,display:inline-block 仅仅一个水平排列方向,就是从左往右,而float可以从右往左排列,这就是两者的差异。然而,我们又有多少情况需要元素从右往左排列呢?很少。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>fl0at</title>
<style type="text/css">
#Content{
    height:600px;   
    margin-top:20px;
    background:#90C;
    
}
</style>
</head>
 
<body>
    <div id="Content">
        <div style="display:inline-block ;height:400px; background:#f00;">Content-Left</div>
        <div style="display:inline-block ;height:400px; background:#fff;">Content-Main</div>       
        <div style="display:inline-block ;margin-right:0px;padding-right:0px;height: 50px; background-color: red;">左浮动</div>  
        <div style="display:inline-block ;margin-left:0px;padding-left:0px;height:50px;background-color: blue;">">右浮动</div>         
    </div>
</body>
</html>
View Code

float详解
先上一个简单示例,了解一下float的使用
float 属性的本质理解
 float 实现页面布局

 float 实现页面布局

        浮动可以实现一行多列。

        对一个元素声明clear:both,会将来自元素周围的的浮动清除,举一个简单的例子就是当先声明一个元素向左浮动时,那么这个元素的右边就会留出一部分空白,如果这个时候空间可以容下该元素的下一个元素的大小,那么由于此元素声明过浮动向左,那么下一个元素就会自动弥补留下的空间。那么相对这个补缺的元素(本身没有声明浮动),它有一个来自他左方的浮动,如果这个时候对这个补缺的元素声明clear: both;那么它就会忽略上一个元素的浮动声明而不去补之前的空缺。对#div1和#div2都声明了浮动向左,这个时候#div1之前是没有其他浮动元素的,clear:both并不会对之后的#div2产生影响,而相对#div2,由于它之前的#div1声明向左浮动,也就给#div2留出了一部分空间,那么由于#div1声明的向左浮动,#div2默认会自动补全,这个时候再对#div2声明clear:both就会起作用,它就跑到下面去了。若限制了parent元素的宽为100pixel,即使#div1向左浮动,也没有空间给#div2补全了,所以#div2只能跑下面去。