Ben Pearson
Ben Pearson

Reputation: 123

A simple CSS float example

Have a look at this example pen:

http://codepen.io/benpearson/pen/bHJke

Is it possible to get div Four and Five to move up beside div Two WITHOUT changing the HTML or using absolute positioning?

(I can't use contains as each div will be floated in different directions depending on screen size.)

.wrap {
  background-color: #666;
  max-width: 500px;
  height: 200px;
  margin: 0 auto;
}

.one {
  background-color: #ddd;
  height: 110px;
  width: 25%;
  float: left;
}

.two {
  background-color: #ccc;
  height: 55px;
  width: 50%;
  float: left;
}

.three {
  background-color: #bbb;
  height: 35px;
  width: 50%;
  float: left;
}

.four {
  background-color: #aaa;
  height: 20px;
  width: 25%;
  float: right;
}

.five {
  background-color: #999;
  height: 20px;
  width: 25%;
  float: right;
}
<div class="wrap">
  <div class="one">
    One
  </div>
  <div class="two">
    Two
  </div>
  <div class="three">
    Three
  </div>
  <div class="four">
    Four
  </div>
  <div class="five">
    Five
  </div>
</div>

Upvotes: 2

Views: 212

Answers (3)

Ben, the div's 4 and 5 will never start from the top 0 of wrapper, because the div 3 starts on the end of div 2. So 4 and 5 recognize the right-upper corner of div 3 as starting point. You must use position: absolute; .. no other choice as far as I know.

Upvotes: 0

Alohci
Alohci

Reputation: 82976

Does this work for you? http://codepen.io/anon/pen/bAzch

Just changed divs four and five to be display:inline-block; instead of float:right;

Upvotes: 4

Michael Peterson
Michael Peterson

Reputation: 1123

Sure, just put a container div around divs two and three and move their float and width properties to it instead.

HTML:

<div class="wrap">
  <div class="one">
    One
  </div>
  <div class="rowtwo">
  <div class="two">
    Two
  </div>
  <div class="three">
    Three
  </div>
  </div>
  <div class="four">
    Four
  </div>
  <div class="five">
    Five
  </div>
</div>

CSS:

.rowtwo {
  float: left;
  width: 50%;
}
}
.two {
  background-color: #ccc;
  height: 55px;

}

.three {
  background-color: #bbb;
  height: 35px;

}

You can see it at: http://codepen.io/anon/pen/KABoC

Upvotes: 0

Related Questions