float

float属性用于创建浮动框,直到左边缘或者右边缘以及包含块或者另一个浮动框的边缘

不加float属性的时候
效果如下

float属性(左浮动)的时候
效果如下

float属性(右浮动)的时候
效果如下

float属性(左右浮动)的时候
效果如下

浮动特性-脱标

  1. 浮动的元素会脱离标准流
  2. 浮动的元素会一行内显示并且元素顶部对齐
  3. 浮动的盒子不再保留原先的位置

浮动特性-浮动元素-一行显示

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css/float.css"> </head> <body> <div class="right_0"></div> <div class="right_1">右1</div> <div class="right_2">右2</div> </body> </html>

css和页面效果如下

如果多个盒子都设置了浮动,那么它们会按照属性值一行内显示并且顶端对齐排列

浮动特性-浮动元素具有行内块元素特点

如果行内元素有了浮动,则不需要转换为块级元素,就可以直接给高度和宽度
html

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/float.css"> </head> <body> <span>1</span> <span>2</span> </body> </html>

css

css
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
span { float: left; width: 200px; height: 200px; background-color: pink; }

行内块元素添加float属性后效果:

浮动元素经常和标准流父级搭配使用

为了约束浮动元素的位置,我们网页布局一般采用的策略是:

先用标准流的父元素排列上下的位置,之后内部子元素采取浮动排列左右位置,符合网页布局第一准则

例子:

html
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/float.css"> </head> <body> <div class="father"> <div class="son">1</div> <div class="son">2</div> <div class="son">3</div> <div class="son">4</div> <div class="son">5</div> <div class="son">6</div> <div class="son">7</div> <div class="son">8</div> <div class="son">9</div> </div> </body> </html>
css
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
.father { width: 500px; height: 500px; background-color: gray; margin: 0 auto; position: absolute; top: 50px; bottom: 0; left: 0; right: 0; } .son { float: left; width: 125px; height: 125px; background-color: pink; margin-left: 20px; margin-top: 20px; }

像上面这样,我们就再标准流的父盒子里创建了两个子盒子
效果图: