Float Creates Overlapping Divs

前端 未结 5 556
小鲜肉
小鲜肉 2021-02-05 20:43

I have two divs (one inside of the other) and am running into a bit of a problem when I float the one inside to \"left\". The problem is that the outer div doesn\'t expand its

相关标签:
5条回答
  • 2021-02-05 21:03

    Maybe handy to note that there is also the well know clearfix code from positioniseverything that is written specifically for this problem and is probably most robust and easiest to apply in any situation. The CSS looks as follows:

    <style>
    div.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
    div.clearfix { display: inline-block; margin: 0 0 8px 0; }
    /* Hides from IE-mac \*/
    * html div.clearfix { height: 1%; }
    div.clearfix { display: block; }
    /* End hide from IE-mac */
    </style>
    

    In order to use it in your situation you would do the following:

    <body>
    <div id="div1" class="clearfix" >Inner Div:
    <div id="div2">Testing long content.</div>
    </div>
    </body>
    
    0 讨论(0)
  • 2021-02-05 21:15

    (The third time today :-) ) give the outer div overflow: hidden;
    and width.

    0 讨论(0)
  • 2021-02-05 21:17

    If you don't want to add additional markup to your html or add a width to your outer div, you can use:

    #div1 {
        overflow:hidden;   /* clears float for most browsers */
        zoom:1;            /* clears float for IE6           */
        }
    
    0 讨论(0)
  • 2021-02-05 21:20

    You need to use the clear-fix. Insert the following after your floated div, and within the containing div.

    <div class="clear"></div>
    

    And add the following style:

    .clear { clear:both; }
    

    Example:

    <div class="container">
      <div class="floatedDiv">Hello World</div>
      <div class="clear"></div>
    </div>
    
    0 讨论(0)
  • 2021-02-05 21:21

    While the solutions above should work, I figure it's worth pointing out that there's one magical trick I haven't seen considered yet (in this thread).

    Just float #div1 left. When you float the parent element, it'll automagically clear the child element - fairly useful, really. You could build an entire layout of floated stacks, and then have one final clear at the end, and it'd be fairly reliable.

    0 讨论(0)
提交回复
热议问题