教程集 www.jiaochengji.com
教程集 >  CSS教程  >  经典实例  >  正文 CSS浮动与清除浮动(overflow)例子

CSS浮动与清除浮动(overflow)例子

发布时间:2017-12-13   编辑:jiaochengji.com
教程集为您提供CSS浮动与清除浮动(overflow)例子等资源,欢迎您收藏本站,我们将为您提供最新的CSS浮动与清除浮动(overflow)例子资源
在css中浮动与清除浮动功能是我们开发中常用到的一个功能了,下面小编来为各位分析关于CSS浮动与清除浮动(overflow)例子吧.

float脱离文本流,可是为什么文字却会有环绕的效果,这点实在是神奇,于是乎就去问了师匠:

Normal flow is the way that elements are displayed in a web page in most circumstances. All elements in HTML are inside boxes which are either inline boxes or block boxes.

float其实是脱离了常规流,当然这么说肯定是听不懂的啦,我们来看一个示例:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>文字环绕</title>
 <style type="text/css">
  html, body {
   margin: 0 auto;
   padding: 0;
  }

  .container {
   width: 300px;
  }
  div {
   box-sizing:border-box;
  }
  img {
   float: left;
  }
  .div1 {
   border: #c2ffaa 2px solid;
   height: 50px;
   width: 20px;
   float: left;
  }

  .div2 {
   border: #e7a6b2 2px solid;
   height: 50px;
   width: 70px;
  }

  .div3 {
   border: #a2c5e2 2px solid;
   height: 50px;
   width: 20px;
  }
 </style>
</head>
<body>
<div class="container">
 <!-- <img src="logo2013.png">
 <p>这是一段文字,This is Chinese, this is English,Hello World, Hello Sky....</p> -->
 <div class="div1"></div>
 <div class="div2">1</div>
 <div class="div3"></div>
</div>
</body>
</html>

好了,很显然,有一种看上去覆盖的效果,实际上,这是由渲染次序决定的:

A float can overlap other boxes in the normal flow (e.g., when a normal flow box next to a float has negative margins). When this happens, floats are rendered in front of non-positioned in-flow blocks, but behind in-flow inlines.

如果一个 float 元素覆盖在了一个在常规流里的元素 那么 float 元素会在没有用 position 定位的块级元素之前渲染

看看,又和position扯上关系,而且position还能决定渲染顺序,顿时感觉好麻烦。

而至于文字,不多说,基本上属于渲染设定类,人家就是会避开浮动部分显示。

在使用浮动的时候经常会遇到一个古怪的事情:

img {
  float: right;
}

<center>\'CSS浮动与清除浮动(overflow)例子\'</center>

 

 

见证奇迹的时刻到了!有一种比较丑陋的方法可以解决这个问题,它叫做清除浮动(clearfix hack).

让我们加入一些新的CSS样式:

.clearfix {
  overflow: auto;
}
现在再看看发生了什么:

 

<center>\'CSS浮动与清除浮动(overflow)例子\'</center>

 

这个可以在现代浏览器上工作。如果你想要支持IE6,你就需要再加入如下样式:

.clearfix {
  overflow: auto;
  zoom: 1;
}
有些独特的浏览器需要“额外的关照”。清除浮动这谭水很深很深,但是这个简单的解决方案已经可以在今天所有的主要浏览器上工作。

您可能感兴趣的文章:

[关闭]
~ ~