CSS 中浮动的使用

float
  none 正常显示
  left 左浮动
  right 右浮动
clear
  none 允许两边浮动
  left 不允许左边浮动
  right 不允许右边浮动
  both 不允许两边浮动

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>CSS 中浮动的使用</title>
 6 <style type="text/css">
 7 .div1{
 8     background-color:#0F0;
 9     width:200px;
10     height:200px;
11     float:left;
12 }
13 .div2{
14     background-color:#0FF;
15     width:200px;
16     height:200px;
17     float:left;
18 }
19 .div3{
20     background-color:#000;
21     width:200px;
22     height:200px;
23     float:left;
24 }
25 .div4{
26     background-color:#FF0;
27     width:200px;
28     height:200px;
29     float:left;
30 }
31 </style>
32 </head>
33 <body>
34 <div class="div1"></div>
35 <div class="div2"></div>
36 <div class="div3"></div>
37 <div class="div4"></div>
38 </body>
39 </html>

浮动的特点:

  1.使块元素在一行显示

  2.使内嵌支持宽高

  3.不设置宽度的时候宽度由内容撑开

内联元素加了浮动之后,变得可以设置宽高

<style>
    span{ width:100px; height:100px; background:red; float:left;}
</style>
<body>
    <span>asf</span>
    <span>fdsaf</span>
</body>

元素加了浮动之后,就相当于漂浮到了上层,下面的元素就会在下层,当时下层元素里面的内容还是会被上层挤出来  如:

<style>
body{ font-size:20px;}
.box1{ width:100px;height:100px;background:red; float:left;}
.box2{ width:200px;height:200px;background:blue;}
</style>
</head>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
</body>

第一个div浮动了浮到上层,第二个div被第一个盖住,但是第二个div中的内容会被挤出来

<style>
body{ font-size:20px;}
.box1{ width:200px;height:200px;background:red; float:left;}
.box2{ width:200px;height:200px;background:blue;}
</style>
</head>
<body>
<div class="box1">box1</div>
<div class="box2">box2</div>
</body>

浮动产生的问题和清除浮动的方法

<style>
body{margin:0;}
.box{width:400px; margin:0 auto; border:1px solid red; height:100px;}
.left{width:300px; height:300px; border:1px solid green;}
/*当父元素没设定高度的时候,子元素设定了高度是可以撑开父元素的,但是当父元素设定了高度或者子元素设定浮动后脱离文档流后就不能了*/
</style>
</head>
<body>
<div class="box">
    <div class="left"></div>
</div>
</body>
<style>
body{margin:0;}
.box{width:400px; margin:0 auto; border:1px solid red;  float:left;}
.left{width:300px; height:300px; border:1px solid green;}
/*当父元素没设定高度的时候,子元素设定了高度是可以撑开父元素的,但是当父元素设定了高度或者子元素设定浮动后脱离文档流后就不能了*/
/*当父元素也浮动的时候又能包住子元素了,前提是父元素不设置小于子元素的高度和宽度,但这种方法不实用,导致margin:0 auto的居中无效了,而且当父元素还用父元素的时候,就要再一层层往上加浮动这样很麻烦*/
</style>
</head>
<body>
<div class="box">
    <div class="left"></div>
</div>
</body>
父级浮动                            问题:页面中所有元素都加浮动,margin左右自动失效(floats bad !)
 
 
 
 
inline-block 清浮动方法: 问题:margin左右自动失效;

定位来清楚浮动

<style>
#box1{border:30px solid red; position:fixed;}
#box2{ width:300px; height:300px; background:blue; float:left;}/*子元素加了浮动之后,脱离了文档流,包不住子元素,父元素就可以加上绝对定位或者浮动点位*/
</style>
</head>
<body>
<div id="box1">
    <div id="box2"></div>
</div>
</body>
原文地址:https://www.cnblogs.com/LO-ME/p/3587891.html