htmlcss

why do divs disappear when using float with %?


It seems that when I use float and % for width, the other divs disappear:

#banner {
  margin-top: 30px;
}

#container {
  width: 80%;
  margin: auto;
}

.right {
  float: right;
}

.topimage {
  background: url(img1.jpg) no-repeat;
  background-size: cover;
  width: 20%;
  height: 150px;
}

.bottomimage {
  background: url(img2.jpg) no-repeat;
  background-size: cover;
  width: 20%;
  height: 150px;
}

.bigimage {
  background: url(imgbig.jpg) no-repeat;
  background-size: cover;
  width: 80%;
  height: 300px;
}
<div id="banner">
  <div id="container">

    <div class="right">
      <div class="topimage"></div>
      <div class="bottomimage"></div>
    </div>
    <div class="bigimage"></div>

  </div>
</div>

Now this makes the two smaller divs disappear, oddly when I set the width of the three child divs in pixels, it works just fine..


Solution

  • When using float, the element takes the width of the content with in it. And since you dont't have any content, the width is 0px. So even 100% of 0px is still 0px.

    You should add some width to the "floated div" or add some content in the empty divs.

    .right {
     float: right;
     width: 50%;
    }
    

    Demo