Skip to content Skip to sidebar Skip to footer

How To Get Floated Divs Align To The Top?

The code below can be viewed in this fiddle: http://jsfiddle.net/VgG55/10/ I have the following markup where the divs are placed in the following order:

Solution 1:

jsFiddle: http://jsfiddle.net/VgG55/7/

Here is alternative way to approach the problem.

HTML:

<div class="grid">
    <div class="wide">
        <div>Prio 1</div>
        <div>Prio 4</div>
        <div>Prio 5</div>
        <div>Prio 6</div>
        <div>Prio 7</div>
    </div>
    <div class="narrow">
        <div>Prio 2</div>
        <div>Prio 3</div>
        <div>Prio 3</div>
    </div>
</div>

CSS:

.grid {
    overflow: hidden;
    background-color: gray;
}

.wide {
    background: blue;
    float: left;
    clear: left;
    width: 80%;
}

.narrow {
    background: green;
    float: right;
    clear: right;
    width: 20%;
}

Solution 2:

This is not possible using float, but you can try to use a javascript masonry plugin like:

http://masonry.desandro.com/ or http://isotope.metafizzy.co/

hope that helps!


Solution 3:

If you can resort the divs you could do something like this instead.

HTML

<div class="wrapper">
   <div class="wide">Prio 1</div>
   <div class="wide">Prio 2</div>
   <div class="wide">Prio 3</div>
   <div class="wide">Prio 4</div>
   <div class="wide">Prio 5</div>
   <div class="narrow">Prio 6</div>
   <div class="narrow">Prio 7</div>
   <div class="narrow">Prio 8</div>
</div>

CSS

* {
   margin: 0;
   padding: 0;
}
.wide {
    background: gray;
    float: left;
    width: 80%;
}

.narrow {
    background: green;
    width: 20%;
    margin-left: 80%;
}

Solution 4:

For equal-sized boxes

use inline-block, but not float, for the wide class

.wide {
  background: gray;
  display:inline-block;
  width: 80%;
}

Demo


For variable-sized boxes

The above method doesn't work well with boxes of different heights, as the floated elements try to maintain the height of the original row, or something.

I managed to hack together something ugly but functional using flex-box:

.wrapper {
  display:flex;
  flex-direction:column;
  /* adjust for the relative re-positioning
     from the hack, below */
  margin-bottom:-150px; 
}
.wide {
  order:0; /* re-order the wide elements to the "start", i.e. top */
  width:79%; /* this could be done with flex:xxx */
}
.narrow {
  order:1; /* re-order the narrows to the "end" */
  align-self:flex-end; /* moves the narrows to the right */
  width:20%; /* again this could be flex:xxx */
  /* the awful hack: */
  position:relative;
  top:-150px; /* magic number: trial and error required */
}

Flexbox should be able to do a 2-column stack. Unfortunately it's not yet supported in Firefox (looks like it's due in v28, so mid-March maybe). Also, I couldn't get it to work in a fiddle in Chrome.

Demo


Post a Comment for "How To Get Floated Divs Align To The Top?"