nightclub nightclub - 2 years ago 68
HTML Question

Margin on the bottom of a div when using float left on HTML5

I don't understand why the following code creates a margin just below the yellow div?. The following code is HTML5 (see the doctype). If you remove the doctype so it's not HTML5 then there is no margin (how I like). The point is that this code must be in HTML5 (that's a requirement for me). Also the yellow div must have width:300px (that's a requirement for me).

Given the circumstances, how can I get rid of the margin below the yellow div?

<!DOCTYPE html>
<div style="background-color:#00f;">
<div style="display:inline-block;width:300px;background-color:#ff0;">
<div style="float:left;">Hello</div>
<div style="float:right;">World</div>

You can check the above code on:

You have a preview here:

enter image description here

I have tried using "clear:both;" with no success.

Any idea on how to solve this?
Could you modify the jsfiddle code in order this to work?

Answer Source

It's the display: inline-block; that creates the space. But your html is a bit off, you need to clearfix the div when using float.

check the fiddle

<div style="background-color:#00f;">
  <div class="clearfix" style="width:300px;background-color:#ff0;">
    <div style="float:left;">Hello</div>
    <div style="float:right;">World</div>

.clearfix:after {
    content: "";
    display: table;
    clear: both;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download