user1970793
user1970793

Reputation: 33

How do i align a div to top

Ok so I set my wordpress content to all float left of each other. So it will be 3 columns.

Now when the title of one div is longer, the boxes are all over the place. Here is what I mean (see image below)

enter image description here

Notice that the james brown title is longer and the other two boxes fall way down.

How can I get them to float up no matter how long a title is.

I have tried vertical-align:top; but that doesn't work

Upvotes: 0

Views: 160

Answers (2)

zessx
zessx

Reputation: 68810

You can get it by two ways.

If you want your boxes top-aligned on each row : simply use a .clear element.

h2 {
    font-weight: bold;
    clear: left;    
}
.box { 
    width: 50px;
    min-height: 50px;
    background: #ccc;
    margin: 3px;
    padding: 3px;
    float: left;
}
.clear {
    clear: both;
    height: 0px;
}
<h2>Without columns</h2>
<div class="box">1 Lorem Ipsum</div>
<div class="box">2 Lorem Ipsum Lorem Ipsum</div>
<div class="box">3 Lorem Ipsum</div>
<p class="clear">&nbsp;</p>
<div class="box">4 Lorem Ipsum Lorem</div>
<div class="box">5 Lorem Ipsum</div>
<div class="box">6 Lorem Ipsum</div>
<p class="clear">&nbsp;</p>
<div class="box">7 Lorem Ipsum</div>
<div class="box">8 Lorem Ipsum</div>

If you want your boxes stucked to the above one, use colums (you'll need to modify a little bit your PHP code)

h2 {
    font-weight: bold;
    clear: left;    
}
.box { 
    width: 50px;
    min-height: 50px;
    background: #ccc;
    margin: 3px;
    padding: 3px;
    float: left;
}
.column {
    width:60px;
    float: left;
}
<h2>With columns</h2>
<div class="column">
    <div class="box">1 Lorem Ipsum</div>
    <div class="box">4 Lorem Ipsum Lorem</div>
    <div class="box">7 Lorem Ipsum</div>
</div>
<div class="column">
    <div class="box">2 Lorem Ipsum Lorem Ipsum</div>
    <div class="box">5 Lorem Ipsum</div>
    <div class="box">8 Lorem Ipsum</div>
</div>
<div class="column">
    <div class="box">3 Lorem Ipsum</div>
    <div class="box">6 Lorem Ipsum</div>
</div>

Upvotes: 2

Dan Blows
Dan Blows

Reputation: 21184

Using the new nth-child() selector, you can do this:

div:nth-child(3n+1) {
  clear:left;
}

This way, the 1st, 4th, 7th, etc, children will move the left of the box 'clearing' all other elements.

The advantage of using this method is that you can adjust the layout responsively. For example, on mobiles you can have two in every row, on large desktops 4 in every row. There's also no non-semantic markup.

The disadvantage is that it doesn't work in IE before version 9, but you can get around that with JavaScript. e.g. jQuery:

// polyfill for browsers that don't support nth-child() CSS selectors
$('.box:nth-child(3n+1)').style('clear', 'left');

See: http://jsfiddle.net/rVHgR/

enter image description here

Upvotes: 0

Related Questions