Search code examples
csshtmloverflowcss-float

How to make a div grow in height while having floats inside


How can I make a div grow its height when it has floats inside of it? I know that defining a value for the width and setting overflow to hidden works. The problem is that I need a div with the overflow visible. Any ideas?


Solution

  • New Answer for 202x:

    In order for a parent to wrap around children elements which are floated, a new block formatting context needs to be set on the parent. This is easily done with:

    .wrap {
        display: flow-root;
    }
    

    or

    .wrap {
        contain: layout;
    }
    

    The latter is a bit newer. Either of these have an advantage over overflow: auto; because they have the explicit purpose of creating a new block formatting context, while overflow: auto works as a side effect. Interestingly, flow-root can be also used alongside block or inline for better layout control. For example:

    .wrap {
        display: inline flow-root;
    }
    

    Read more:


    Original Answer from 2011:

    overflow:auto; on the containing div makes everything inside of it (even floated items) visible and the outer div fully wraps around them. See this example:

    .wrap {
      padding: 1em;
      overflow: auto;
      background: silver;
     }
     
    .float {
      float: left;
      width: 40%;
      background: white;
      margin: 0 1%;
    }
    <div class="wrap">
      <div class="float">Cras mattis iudicium purus sit amet fermentum. At nos hinc posthac, sitientis piros Afros. Qui ipsorum lingua Celtae, nostra Galli appellantur. Petierunt uti sibi concilium totius Galliae in diem certam indicere. Ambitioni dedisse scripsisse iudicaretur.</div>
      <div class="float">Mercedem aut nummos unde unde extricat, amaras. A communi observantia non est recedendum. Quisque ut dolor gravida, placerat libero vel, euismod. Paullum deliquit, ponderibus modulisque suis ratio utitur.</div>
      </div>