1

I am faced with a CSS problem. The situation is as follow:

I have this kind of structure:

#Block {
  background-color: #FF0000;
  padding-top: 30px;
  padding-bottom: 30px;
  padding-left: 30px;
  padding-right: 30px;
}
[class="Element"] {
  width: 33.33%;
  background-color: #0000FF;
  float: left;
}
<div id="Block">
  <div class="Element">
    Some contents.
  </div>
  <div class="Element">
    Some more contents.
  </div>
  <div class="Element">
    Still some more contents.
  </div>
</div>

I was expecting to see a red box behind my 3 elements(blue), containing them.

But I only see a red rectangle behind the elements, but with the wrong size, more precisely not high enough. It seems that the Block part is totally un related to the rest.

What did I do wrong?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Michel
  • 10,303
  • 17
  • 82
  • 179

1 Answers1

1

Clear the floats using this:

#Block:after{
  content:'';
  display:block;
  clear:both;
}

and I guess that looks OK now.

Why this happens?

  1. If the containing blocks have floating elements, then it will get height only if you clear the floating context.(See an example here)

  2. If any one of them are not floated, then the containing block takes the height of this element.

  3. You can also use overflow: hidden on the containing block to get the same effect.

#Block {
  background-color: #FF0000;
  padding-top: 30px;
  padding-bottom: 30px;
  padding-left: 30px;
  padding-right: 30px;
}
[class="Element"] {
  width: 33.33%;
  background-color: #0000FF;
  float: left;
}
#Block:after{
  content:'';
  display:block;
  clear:both;
}
<div id="Block">
  <div class="Element">
    Some contents.
  </div>
  <div class="Element">
    Some more contents.
  </div>
  <div class="Element">
    Still some more contents.
  </div>
</div>
Community
  • 1
  • 1
kukkuz
  • 41,512
  • 6
  • 59
  • 95