css清除浮动

How To Clear Floats Without Structural Markup

(This clearing technique was developed by Tony Aslett, of csscreator.com. 
The earliest known mention of the basic :after idea is found here.)

Notice as of March 4th, 2008: The article you are reading is getting a bit old and much new information on the subject of clearing has appeared since it was written. You may find this newer article very interesting.

Clearing Floats The Old Fashioned Way

When a float is contained within a container box that has a visible border or background, that float does not automatically force the container's bottom edge down as the float is made taller. Instead the float is ignored by the container and will hang down out of the container bottom like a flag. Those familiar only with Explorer for Windows may scratch their heads and say "That's not right!" True, IE/Win does enclose a float within a container 'automatically', but only if the container element happens to possess the MS-only quality called hasLayout.

This float-enclosing behavior in IE can also be 'toggled' off again just by hovering of links within the container, if that hovering alters either the link background or one of several other CSS properties. Quite a mess, and we'll cover it farther along in the article, in the "Toggle Trouble" section.

The W3C suggests placing a "cleared" element last in the container box, which is then recognized by the container height, forcing the container to enclose the float above that cleared element too. It's described more fully our article Float: The Theory:

“..let's say you give that following box the clear property,   {clear: both;} . What this does is extend the margin on the top of the cleared box, pushing it down until it "clears" the bottom of the float. In other words, the top margin on the cleared box (no matter what it may have been set to), is increased  by the browser, to whatever length is necessary to keep the cleared box below the float.”

So in effect, such a cleared box cannot be at the same horizontal level as a preceding float. It must appear just below that level. The image shows how this might look, with a red border representing the container element:

Shows how a box may clear below a float.

The standard method of making an outer container appear to "enclose" a nested float is to place a complete "cleared" element last in the container, which has the effect of 'dragging' the lower edge of the containing box lower than the float. Thus the float appears to be enclosed within the container even tho it really isn't. The code for a cleared box usually looks something like this:

<div> <!-- float container -->
  <div style="float:left; width:30%;"><p>Some content</p></div>
  <p>Text not inside the float</p>
<div style="clear:both;"></div>
</div>

Since that div is not floated, the container must recognize it and enclose it, and because of that top margin (added by the browser because of the "clear" property), the div "pulls" the bottom edge of the container down below the bottom edge of the float.

Problems With The Method

First and foremost, this clearing method is not at all intuitive, requiring an extra element be added to the markup. One of the major premises of CSS is that it helps reduce the bloated HTML markup found it the average site these days. So having to re-bloat the markup just so floats can be kept within their containers is not an ideal arrangement.

Besides that, some browsers can have trouble with certain kinds of clearing elements in some situations. Mozilla is particularly sensitive to clearing problems.

Up 'til now there was no other way to do this, but no more! Thanks to the efforts of Tony Aslett, creator and operator ofcsscreator.com, we can now use advanced CSS to "clear" a float container in non-IE browsers and just let IE keep wrongly clearing itself. The upshot is that we now have the option to avoid adding that pesky clearing element to the HTML markup. Woohoo!

"Clearing", 21st Century Style

In the new method, no clearing element is used. This does not affect IE/Win which simply keeps enclosing the float as always (assuming the container has a stated dimension), but non-IE browsers will need a substitute for that element. Here's how it's done.

Using :after

This CSS 2 property allows extra content to be added at the end of an element via the CSS. That means no actual markup is needed in the HTML. The content is specified from within the CSS stylesheet, and appears in the page as would a real HTML element that had been inserted following all the normal content of the target element. Such :after generated content cannot receive some CSS properties, including 'position', 'float', list properties, and table properties. However, the 'clear' property isallowed. Do you see where we are going here?

Imagine that we use :after to insert a simple character like a 'period', and then give that generated element  {clear: both;} . That's all you really need to do the job, but no one wants a line space messing up the end of their clean container box, so we also use  {height: 0;}  and  {visibility: hidden;}  to keep our period from showing.

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

Notice that  {display: block;}  is also applied to the :after element, because if it isn't then that element defaults to "inline", and cannot receive the "clear" property. Also, Tony's method originally used "overflow: hidden;" to hide the period, but sadly the latest FireFox versions will display the period if this is done.

But what about IE?

Since IE7 does not support the :after pseudoclass yet, we must rely on the same"auto-clearing" effect used for IE6, and that behavior happens when the float-containing element gets hasLayout applied to it. A simple declaration of "zoom: 1;" will perform this trick in IE5.5 and up, but it's proprietary and needs to be hidden in order to validate.

As a side benefit, hasLayout on float-enclosing elements also prevents several other major IE/Win float bugs. However, should this container box be placed following a previous external float, the IE height fix will trigger Microsoft's proprietary and illegalFloat Model, so watch out for that, okay?

Toggle Trouble

It so happens that IE has, well, a little problem with this auto-enclosing behavior. You saw that coming, didn't you. Yes, IE bugs come in big bunches. This one results when that container element has links inside, following the float. When this happens and certain links are hovered, the auto-enclosing behavior is toggled or "switched off", causing the lower edge of the container box to suddenly jump up to the bottom of the non-floated content. Hovering other links restores the behavior. This interesting effect is of course called the IE/Win Guillotine Bug Those of you viewing in IE/Win may play around with the following live demos, and for a more complete explanation see the IE/Win Guillotine Bug demo page .

The toggling only occurs when a:hover is used to change the link background or many other styling changes, such aspaddingmargin, or any font styling on the link. Strangely, having the text color change on hover does not toggle the bug.

The containers are grey with green borders, and the floats are dark brown with yellow borders. Notice how the third and fourth links ouside the floats toggle the Guillotine Bug, and the first two un-toggle it. This seems to be related to the actual text lines themselves, so any links after the first two lines will toggle the effect. Links in the float will all un-toggle the effect. Just more weird IE bug behaviors, folks, nothing "unusual".
Screenshot

Float Link
Any link in this float will restore the cutoff portion, as will the links in the first two text lines outside the float. Something makes those first two lines "special".
Link
Link
Link
Link
Float Link
The non-floated links to the left are wrapped in a paragraph, and that paragraph has the Holly hack value applied to it. Say "buh-bye" to the Guillotine Bug!

Link
Link
Link
Link

 

The second demo has been "fixed" by placing those links in a paragraph, which then gets the zoom fix applied to it. Any block element will do just as well here. Yes, this means another element is needed, but unlike a clearing div, this paragraph is a "semantic" element. Text content really ought to be wrapped in semantic containers anyway, and since we forward-thinking coders always have our content thusly contained, it's easy to apply the same .clearfix class to one more element.

A Word About Floats In Floats

Observant readers will have noticed that the above demos have "enclosed" floats, even in Opera 7 and Mozilla! This is because the demos themselves are floats, and all modern browsers (including IE, luckily) always let floats enclose other floats. Of course there has to be an outer float, and it still threatens to break out of its container...

Putting It Together

First, this code gets added to the CSS stylesheet:

<style type="text/css">

  .clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    }

</style><!-- main stylesheet ends, CC with new stylesheet below... -->

<!--[if IE]>
<style type="text/css">
  .clearfix {
    zoom: 1;     /* triggers hasLayout */
    }  /* Only IE can see inside the conditional comment
    and read this CSS rule. Don't ever use a normal HTML
    comment inside the CC or it will close prematurely. */
</style>
<![endif]-->

For the HTML, just add a class of .clearfix to any element containing a float needing to be cleared, plus any Guillotine-Bug-fixing block elements within the container. That's it! It's not perfect, but it's a whole lot better than adding an entire extra 'dummy' element. Check out this live demo of the fix in action:

This float is not enclosed by the surrounding div container.

This container lacks the fix.

 

See how this float no longer protrudes out of the containing box, with no extra clearing element used in the container!

This float container has a class attribute of "clearfix", which applies the :after fix, or the Holly hack, depending on the browser.

IE/Mac Strikes Back

All this is wonderful, but unfortunately IE for the Mac does not "auto-clear" floats, and also does not support :after, and so is left out of the clearing party. What's to be done?

You might callously abandon IE/Mac, but consider that many people who use older Macs can't run Safari, or several other modern browsers. Thankfully this browser has been dropped by Microsoft, and at some future time the numbers of such IE/Mac users will become miniscule. Remember that even if a float appears to stick out of a container, no content will actually be obscured. It just won't look as pretty for those few viewers, that's all. Each author will have to decide on this issue according to their specific needs.

This page once described a Javascript method to force compliance in IE/Mac, but now thanks to Mark Hadley and Matt Keoghit's now possible to dispense with that ugly Javascript and go with a straight CSS fix. Woohoo!

Taming the IE/Mac Float Problem

Basically the fix is just a matter of applying a display: inline-block; to the .clearfix class, and hiding that property from all other browsers. That's it! We can easily do this with our existing code, slightly modified.

<style type="text/css">

  .clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
    }

.clearfix {display: inline-block;}  /* for IE/Mac */

</style><!-- main stylesheet ends, CC with new stylesheet below... -->

<!--[if IE]>
<style type="text/css">
  .clearfix {
    zoom: 1;     /* triggers hasLayout */
    display: block;     /* resets display for IE/Win */
    }  /* Only IE can see inside the conditional comment
    and read this CSS rule. Don't ever use a normal HTML
    comment inside the CC or it will close prematurely. */
</style>
<![endif]-->

The .clearfix {display: inline-block;} is seen by all browsers, and fixes IE/Mac. Then, inside the rule set that is hidden from IE/Mac, the display is reset to block. That's all she wrote! Simply stick the above code into your CSS, and use .clearfix on any box that has to contain a sizable float. Ain't that cool? Just watch out for previous external floats triggering the IE Float Model, as mentioned earlier.

Kudos to Alex Robinson for finding that inline-block is superior to the older inline-table fix for IE/Mac.

A Word Of Warning (this is important!)

The W3C float specification requires that a cleared element shall stay below all previous floats. There are no exceptions to this requirement! "Previous" in this case means any float that comes earlier in the source document.

Up until November of 2004, Firefox was still incorrectly clearing only the floats that were vertically above the clearing element, rather than all previous floats. This meant that in those earlier Gecko browsers you could place a floated column down one side of the screen, and inside another column (possibly another floated column) you could clear a smaller interior float, without that cleared element dropping below the previous floated column. Since only Gecko had this problem, it was obvious that something was wrong every time this happened to a page. Normally Gecko is the good browser, but in this one case it was the culprit. See, IE is not always the bad guy!

However, this easy clearing method has muddled the issue quite a bit, since now Explorer is not actually being cleared at all, while Gecko browsers have finally been corrected so they do clear all previous floats.


...Oh no! Do you see what will now happen in our hypothetical float page? IE, seeing no real clearing elements, will look great. Meanwhile, in newer Gecko browsers and Opera 7, the CSS generated clearing element in the first easycleared box will drag the height of that box waaaay down the page, until that invisible clearer is vertically below the bottom of the previous float column (assuming there is a bottom!). This can "generate" a huge empty space inside that once-small easycleared box, depending on the actual height of the neighboring float column.

Of course Opera 7 has always correctly implimented the clearing specs just like IE does (aside from bugs), and the Mac browsers are not involved either. If you are wondering how this issue can be fixed, well, it can't. Gecko and Opera are now both following the float clearing specs correctly, and IE only fails because of the faked "clearing" we are forcing upon it.

Preventing External Clearing

If you have the above described problem, one way to prevent the clearer from clearing the adjacent float column is to make the container a float itself. Of course once you float the container you no longer need easyclearing, sigh...

Note that when all the main elements in a column setup are floats, the worst IE float bugs simply do not happen. Thus using an all-float approach to column design can actually be easier to accomplish, at least within a rigid-width layout.

Them That Done It

Thanks to Tony Aslett for showing us the way. His site, csscreator.com is a killer CSS forum where newbies and gurus alike hang out and exchange CSS know-how. Tony's original demo page for this method can be found here, and the relevant forum thread is here.

Kudos also to Doug for pointing out the "period problem" in FireFox, and to Mark Hadley for that elegant IE/Mac fix, and toMatt Keogh for showing how "inline-table" also fixes IE/Mac while using an already-approved CSS property. Once more the CSS community comes thru for us all! :-)


Big John Design   Contact Us ©positioniseverything.net
Last updated: July 2, 2008
Created May 14, 2004

转载于:https://www.cnblogs.com/firefile/archive/2012/06/12/2546607.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 清除浮动的作用是解决父元素因子元素浮动而导致的高度塌陷问题。当所有的子元素浮动时,父元素没有设置高度,就会出现高度塌陷的情况。清除浮动可以使父元素正确地包裹子元素,使得布局更加准确。\[1\]清除浮动的方法有多种,可以使用带clear属性的空元素,在浮动元素后使用一个空元素,并在CSS中赋予.clear{clear:both;}属性即可清理浮动。也可以使用AFTER伪元素,通过父元素的::after伪元素来生成浮动元素的兄弟元素,然后兄弟元素使用clear:both方法。另外,通过BFC给浮动的元素的容器添加浮动,给浮动元素的容器也添加上浮动属性即可清除内部浮动。但是需要注意,这样会使整体浮动,可能会影响布局,不推荐使用。\[2\]清除浮动的本质是为了解决浮动元素不占位置,影响后面元素排版的问题。\[3\] #### 引用[.reference_title] - *1* *3* [css知识点——清除浮动](https://blog.csdn.net/weixin_43894901/article/details/116291924)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [前端基础:CSS清除浮动的原因、本质和方法](https://blog.csdn.net/weixin_49555741/article/details/123412490)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值