MonkeyBusiness
MonkeyBusiness

Reputation: 163

CSS float leaves gap

Given the below simple html, how to stack the green DIVs on top of each other without the space (using or not using floats)? I don't know why there is space between the third and forth green DIVs.

* {
  margin: 0;
}
.left {
  width: 20%;
  background-color: #00CC66;
  height: 50px;
  float: left;
  clear: left;
}
.right {
  width: 20%;
  background-color: #0033FF;
  height: 99px;
  float: right;
  clear: right;
}
<div class="left"></div>
<div class="right"></div>
<div class="left"></div>
<div class="right"></div>
<div class="left"></div>
<div class="right"></div>
<div class="left"></div>
<div class="right"></div>

Upvotes: 0

Views: 2375

Answers (3)

MattDiMu
MattDiMu

Reputation: 5003

A floated div can't be above (in terms of vertical position) a preceding floated element, even if it's floated to the other side. Therefore the 4th green div can't be above the 3rd blue div and is pushed downwards.

Upvotes: 2

Higeath
Higeath

Reputation: 561

Clear div should be in between 'left' & 'right' not on every div.

Solution 1

<div class="left"></div>
<div class="right"></div>
<div style="clear: both;"></div>
<div class="left"></div>
<div class="right"></div>
<div style="clear: both;"></div>
<div class="left"></div>
<div class="right"></div>

css

* {
  margin: 0;
}
.left {
  display: block;
  width: 20%;
  background-color: #00CC66;
  height: 50px;
  float: left;
}
.right {
  width: 20%;
  background-color: #0033FF;
  height: 50px;
  float: right;
}

A little clearner

Solution 2

<div class="left"></div>
<div class="right"></div>
<div class="clr left"></div>
<div class="right"></div>
<div class="clr left"></div>
<div class="right"></div>
<div class="clr left"></div>
<div class="right"></div>

css:

* {
  margin: 0;
}
.left {
  display: block;
  width: 20%;
  background-color: #00CC66;
  height: 50px;
  float: left;
}
.right {
  width: 20%;
  background-color: #0033FF;
  height: 50px;
  float: right;
}

.clr{
  clear: both;
}

Upvotes: 0

Aditya Mehta
Aditya Mehta

Reputation: 21

change this in style tag : .left { width: 20%; background-color: #00CC66; height: 70px; float: left; clear:left;}

Upvotes: -1

Related Questions