什么是浮动float

浮动不是一个正常流布局,浮动元素会从文档的正常流中删除,但是他还是会印象布局,浮动应用于所有的元素,当一个元素浮动时,其他内容会“环绕”该元素。

float属性有四个值:left,right分别浮动元素到相应的方向,none(默认),使元素不浮动,inherit将从父级元素获取float值

float用处

可用来创建全部网页布局,如导航条的一行排列,左右两栏布局 ,浮动在左右两栏布局中很常见。

例:

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        body{text-align: center}
        #container{
            width:500px;  height:auto;  margin:auto;
        }
         #header{
             width:500px;  height:100px;  background-color: red;
         }
         #left{
            width:130px;  height:300px;  background-color: green;  float:left;
         }
         #right{
             width:350px;  height:300px;  background-color: blue;  float:right;
         }
        #footer{
            width:500px; height:100px; background-color: yellow; /*clear:both;*/
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="header">header</div>
        <div id="left">side bar</div>
        <div id="right">main content</div>
        <div id="footer">footer</div>
    </div>
</body>
</html>

 

清除浮动之后

浮动造成的塌陷问题

如果父元素只包含浮动元素,那么它的高度就会塌陷为零,如果父元素不包含任何的可见背景,这个问题是很难注意到的。

解决父元素塌陷问题

1、可以为父级元素设置一个height

2、可以为父级元素设置overflow:hidden;

3、可以为父级元素设置一个dislplay:inline-block;

为父级元素设置一个dislplay:inline-block;效果

清除浮动的技巧

 如果很明确知道接下来的元素会是什么,则可以使用clear:both;来清除浮动此外还有以下清除方法

1、使用空的div方法

2、利用overflow属性, 如果父元素的这个属性设置为 auto 或者 hidden,父元素就会扩展以包含浮动。

3、简单且较聪明的清除方法(css伪选择符 :after)来清除浮动,但是需要紧挨着浮动元素

    #container:after{
            display: block;
            content: ' ';
            clear:both;
        }

 

posted @ 2016-06-21 22:08  hy_sunny  阅读(2973)  评论(0编辑  收藏  举报