1

假设你有一个文章列表,有些有一个右浮动的图像和很少的文字,所以图像漂浮在文章之外并进入下一篇文章,把事情搞砸了。

确保文章内的元素不会漂浮在文章之外的正确/首选/最佳方法是什么?

我知道这overflow:hidden行得通,但这是正确的用法吗?还是只是碰巧做我想做的事?

4

3 回答 3

5

You have three ways to do it:

  1. you can have overflow:hidden which is a clean way to do it.

    • Pros: It does not mess with semantics of the HTML, No "dead elements".
    • Cons: clipping the content if the container has a defined dimension, and clips shadows from inner elements.

      div        <-- style="overflow:hidden"
          div    <-- floating children
          div    
      div        <-- style="overflow:hidden"
          div    <-- floating children
          div
      
  2. You can have a blank element, usually a <div> after the container that has floats. Style this with clear:both.

    • Cons: Having a "dead element" in the DOM.

      div
          div    <-- floating children
          div 
      div        <-- style="clear:both"
      div 
          div    <-- floating children
          div 
      
  3. You can add a "clearfix" class to the container and use :after pseudo-class to add a "clearing dynamic dot/space". Basically it works like the second, but uses the :after to insert a space that has "clear:both" This article explains it.

    • Pros: It does not mess with semantics of the HTML, No "dead elements".
    • Cons: "classitis" (overuse of classes), :after is not supported in IE7 and older, thus CSS hacks are used

      div        <-- :after
          div    <-- floating children
          div
      " "        <-- style="clear:both"
      div        <-- :after
          div    <-- floating children
          div
      

You can use either of the three and they work great. I usually use 1 most of the time, and if I had shadows in the container, or if the container has a fixed dimension, I use 3. Method 3 relies on :after which is new. To support this clearfix, youd use an old CSS hack as described in the article.

于 2012-05-27T21:10:39.633 回答
2

对于每个文章元素,添加clear: both;. 这将确保图像不会在下一篇文章中“泄漏”,同时也确保它们不会被截断。

于 2012-05-27T21:03:20.147 回答
1

该链接准确地解释了您的要求。

overflow: hidden 或 overflow: auto 将是清除较小包含元素上的浮动的可接受的解决方案,例如包含浮动列表项的导航栏,或具有一堆浮动框的号召性用语区域。

并且链接还用demo解释了使用overflow:hidden清除的问题。

于 2012-05-27T21:12:07.103 回答