转载http://css-tricks.com/795-all-about-floats/

All About Floats

by: Chris Coyier

Jul 8 2009
119

What is "Float"?

Float is a CSS positioning property. To understand its purpose and origin, we can look to print design. In a print layout, images may be set into the page such that text wraps around them as needed. This is commonly and appropriately called "text wrap". Here is an example of that.

In page layout programs, the boxes that hold the text can be told to honor the text wrap, or to ignore it. Ignoring the text wrap will allow the words to flow right over the image like it wasn't even there. This is the difference between that image being part of the flow of the page (or not). Web design is very similar.

In web design, page elements with the CSS float property applied to them are just like the images in the print layout where the text flows around them. Floated elements remain a part of the flow of the web page. This is distinctly different than page elements that use absolute positioning. Absolutely positioned page elements are removed from the flow of the webpage, like when the text box in the print layout was told to ignore the page wrap. Absolutely positioned page elements will not affect the position of other elements and other elements will not affect them, whether they touch each other or not.

Setting the float on an element with CSS happens like this:

#sidebar {     float: right;  }

There are four valid values for the float property. Left and Right float elements those directions respectively. None (the default) ensures the element will not float and Inherit which will assume the float value from that elements parent element.

What are floats used for?

Aside from the simple example of wrapping text around images, floats can be used to create entire web layouts.

Floats are also helpful for layout in smaller instances. Take for example this little area of a web page. If we use float for our little avatar image, when that image changes size the text in the box will reflow to accommodate:

This same layout could be accomplished using relative positioning on container and absolute positioning on the avatar as well. In doing it this way, the text would be unaffected by the avatar and not be able to reflow on a size change.

Clearing the Float

Float's sister property is clear. An element that has the clear property set on it will not move up adjacent to the float like the float desires, but will move itself down past the float. Again an illustration probably does more good than words do.

In the above example, the sidebar is floated to the right and is shorter than the main content area. The footer then is required to jump up into that available space as is required by the float. To fix this problem, the footer can be cleared to ensure it stays beneath both floated columns.

#footer {     clear: both;  }

Clear has four valid values as well. Both is most commonly used, which clears floats coming from either direction. Left and Right can be used to only clear the float from one direction respectively. None is the default, which is typically unnecessary unless removing a clear value from a cascade. Inherit would be the fifth, but is strangly not supported in Internet Explorer. Clearing only the left or right float, while less commonly seen in the wild, definitely has its uses.

The Great Collapse

One of the more bewildering things about working with floats is how they can affect the element that contains them (their "parent" element). If this parent element contained nothing but floated elements, the height of it would literally collapse to nothing. This isn't always obvious if the parent doesn't contain any visually noticeable background, but it is important to be aware of.

As anti-intuitive as collapsing seems to be, the alternative is worse. Consider this scenario:

If the block element on top where to have automatically expanded to accomodate the floated element, we would have an unnatural spacing break in the flow of text between paragraphs, with no practical way of fixing it. If this were the case, us designers would be complaining much harder about this behavior than we do about collapsing.

Collapsing almost always needs to be dealt with to prevent strange layout and cross-browser problems. We fix it by clearing the float after the floated elements in the container but before the close of the container.

Techniques for Clearing Floats

If you are in a situation where you always know what the succeeding element is going to be, you can apply the clear: both; value to that element and go about your business. This is ideal as it requires no fancy hacks and no additional elements making it perfectly semantic. Of course things don't typically work out that way and we need to have more float-clearing tools in our toolbox.

  • The Empty Div Method is, quite literally, an empty div. <div style="clear: both;"></div>. Sometimes you'll see a <br /> element or some other random element used, but div is the most common because it has no brower default styling, doesn't have any special function, and is unlikely to be generically styled with CSS. This method is scorned by semantic purists since its presence has no contexual meaning at all to the page and is there purely for presentation. Of course in the strictest sense they are right, but it gets the job done right and doesn't hurt anybody.
  • The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats, effectively clearing it for succeeding elements. This method can be beautifully semantic as it may not require an additional elements. However if you find yourself adding a new div just to apply this, it is equally as unsemantic as the empty div method and less adaptable. Also bear in mind that the overflow property isn't specifically for clearing floats. Be careful not to hide content or trigger unwanted scrollbars.
  • The Easy Clearing Method uses a clever CSS pseudo selector (:after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class like "clearfix" to it. Then apply this CSS:
    .clearfix:after {     content:".";     visibility: hidden;     display: block;     height:0;     clear: both;  }

    This will apply a small bit of content, hidden from view, after the parent element which clears the float. This isn't quite the whole story, as additional code needs to be used to accomodate for older browsers.

Different scenarios call for different float clearning methods. Take for example a grid of blocks, each of different types.

To better visually connect the similar blocks, we want to start a new row as we please, in this case when the color changes. We could use either the overflow or easy clearing method if each of the color groups had a parent element. Or, we use the empty div method in between each group. Three wrapping divs that didn't previously exist or three after divs that didn't previously exist. I'll let you decide which is better.

Problems with Floats

Floats often get beat on for being fragile. The majority of this fragility comes from IE 6 and the slew of float-related bugs it has. As more and more designers are dropping support for IE 6, you may not care, but for the folks that do care here is a quick rundown.

  • Pushdown is a symptom of an element inside a floated item being wider than the float itself(typically an image). Most browsers will render the image outside the float, but not have the part sticking out affect other layout. IE will expand the float to contain the image, often drastically affecting layout. A common example is an image sticking out of the main content push the sidebar down below.

    Quick fix: Make sure you don't have any images that do this, use overflow: hidden to cut off excess.

  • Double Margin Bug - Another thing to remember when dealing with IE 6 is that if you apply a margin in the same direction as the float, it will double the margin. Quick fix: set display: inline on the float, and don't worry it will remain a block-level element.
  • The 3px Jog is when text that is up next to a floated element is mysteriously kicked away by 3px like a weird forcefield around the float. Quick fix: set a width or height on the affected text.
  • In IE 7, the Bottom Margin Bug is when if a floated parent has floated children inside it, bottom margin on those children is ignored by the parent. Quick fix: using bottom padding on the parent instead.

Alternatives

If you need text wrapping around images, there really aren't any alternatives for float. Speaking of which, check out this rather clever technique for wrapping text around irregular shapes. But for page layout, there definitely are choices. Eric Sol right here on A List Apart has an article on Faux Absolute Positioning, which is a very interesting technique that in many ways combines the flexibility of floats with the strength of absolute positioning. CSS3 has the Template Layout Module that, when widely adopted, will prove to be the page layout technique of choice

转载于:https://www.cnblogs.com/mackxu/archive/2011/11/27/2264844.html

All About Floats相关推荐

  1. Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for i

    keras  imshow显示图片显示不出来,报错 Clipping input data to the valid range for imshow with RGB data ([0..1] fo ...

  2. Floats and marginpars not allowed inside `multicols' Unknown float option `H'. 基于LaTex+VSCode+MAC

    错误提示: Floats and marginpars not allowed inside 'multicols' environment!. Unknown float option H'. 原因 ...

  3. 《Guava Floats类》学习笔记

    Floats是float基本类型的实用工具类. 类声明 以下是com.google.common.primitives.Floats类的声明: @GwtCompatible(emulated=true ...

  4. 理解CSS Floats

    原作者:Steven Bradley 发表时间:2009年10月15日 原文链接:http://www.vanseodesign.com/css/understanding-css-floats/ 翻 ...

  5. 在CSS布局中让Floats轻拂

    If you're new to CSS layouts, you'd be forgiven for thinking that using CSS floats in imaginative wa ...

  6. latex文件里面一个章节放的图表太多编译出现oo many unprocessed floats的解决方案

    当latex文件里面一个章节放的图表太多(超过18个)时,编译的时候会报错: Too many unprocessed floats. 原因: latex会把不能处理的浮动的图形放到 "未处 ...

  7. Clearing Floats清除浮动--clearfix的不同方法的使用概述

    清除浮动早已是一个前端开发人员必学的一课.毫无疑问,多年来,我们已经接触过多种清除浮动的方法,现在"clearfix methods"越来越被大家熟知.在深入剖析"cle ...

  8. too many unprocessed floats

    前面已经引用过,在latex中,当浮动图形过多时,会出现提示错误. 此时,如果图形不是特别多,可以用以前已经介绍的方法.但是,如果浮动图形太多,就不行了.此时,只能用另外一个办法,就是人工设置浮点位置 ...

  9. Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255]解决方法

    Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] ❓报错原因 ...

最新文章

  1. 使用JNDI操作LDAP(5)(转载)
  2. java的断点条件,java – Eclipse Debugger不会在条件断点处停止
  3. 在Python中用Selenium执行JavaScript
  4. 041_Unicode对照表七
  5. margin-top的百分比是相对父元素的哪个值
  6. iOS-Runtime知识点整理
  7. 华为交换机telnet和ftp服务开启/关闭命令
  8. java中的几个集合类
  9. MySQL · 答疑解惑 · MySQL Sort 分页
  10. 联想教育应用使用说明(7.6版本)——第4章 网络控制工具的使用
  11. dw常用标签_DW代码大全
  12. 工业交换机的管理方式有哪些?
  13. 小球弹跳及MATLAB实现
  14. CSDN日报20170224——《程序员该用哪种姿势来理财》
  15. linux yum 安装播放器,centos5下用yum安装MPlayer播放器
  16. Resultful接口实现后端文件下载
  17. python绘制条形图 中文横坐标_python3使用matplotlib绘制条形图
  18. 百度地图框选标注坐标返回标注信息
  19. https自签证书tls握手时错误或go系统错误处理
  20. 考研网络100基础知识

热门文章

  1. 转杨毅:火箭输得有谱了!
  2. ceph存储 smartctl用法小结
  3. 阿里云服务器ECS Ubuntu16.04-64-bit学习之一:配置桌面(进阶-脚本一键执行)
  4. 求阶乘序列前N项和(15分)
  5. 好书读不完,常存常读常更新
  6. 少年为了学计算机的电影,少年十大励志电影排行榜 能改变人生的励志电影推荐...
  7. sql xml 带冒号_Jupyter与SQL魔法
  8. LeetCode 每日一题:606. 根据二叉树创建字符串
  9. 我们都忽略了Html5的力量,如果只看成一种技术就大错特错了!
  10. 电影推荐:阿兰·图灵--一个伟大而又悲惨的天才