user632347
user632347

Reputation: 835

How to make divs floating next to one another?

Aim : I want to make my divs floating next to one another like this.

http://jsfiddle.net/x8Abc/1/

.post {
   float:left;
   padding:10px;
   margin:5px;
   border:1px solid #000;
   width:25%;
}

Problem : when I have a content which of of more length in an in between div, then it is pushing the div below it to side like this.

http://jsfiddle.net/W3afJ/

.post {
   float:left;
   padding:10px;
   margin:5px;
   border:1px solid #000;
   width:25%;
}

How can I achieve a uniform well packed layout like jsfiddle.net/x8Abc/1/ ?

Upvotes: 1

Views: 150

Answers (2)

CherryFlavourPez
CherryFlavourPez

Reputation: 7487

You have a few different options:

  1. Give each of your posts a fixed height, and set the overflow property to auto. This will (obviously) ensure that each is the same height and so avoid the issue where one floats next to its sibling, but will add scrollbars to divs with a lot of text, and blank space to the bottom of those with little (see it here):

    .post {
        float: left;
        padding:10px;
        margin:5px;
        border:1px solid #000;
        width:25%;
        height: 250px;
        overflow: auto;
     }
    
  2. Stick with float to lay out your posts, and ensure that the first post in each row is cleared (see it in action) . That can be achieved like this*:

    .post:nth-child(3n + 1) { clear:both; }
    
  3. Change your approach to laying out your posts to use inline-block, like this:

    .post {
        display: inline-block;
        padding:10px;
        margin:5px;
        border:1px solid #000;
        width:25%;
     }
    

There is a fork of your original example here. I would recommend going with this approach, as it gives you the ability to vertically-align your posts as you see fit, and won't restrict the amount of copy in each like option 1. This article is a good read, and details how to get it working even in older browsers.

* Note that IE<9 won't support the nth-child pseudo-class, so you'd need a JavaScript fallback for those browsers.

Upvotes: 2

Sean
Sean

Reputation: 6499

You need to use display: inline-block in this situation.

Amend your css like so:

.post {
   display: -moz-inline-stack;
   display: inline-block;
   *display: inline;
   padding: 10px;
   margin: 5px;
   border: 1px solid #000;
   width: 25%;
   zoom: 1;
}

Here's a fiddle as well

To align the blocks vertically change the vertical-align css property, e.g.

.post {
   display: -moz-inline-stack;
   display: inline-block;
   *display: inline;
   padding: 10px;
   margin: 5px;
   border: 1px solid #000;
   width: 25%;
   zoom: 1;
   vertical-align: top;
}

For more information on making display: inline-block work in IE (as I have done above) see here:

https://blog.mozilla.org/webdev/2009/02/20/cross-browser-inline-block/

Upvotes: 3

Related Questions