Skip to content Skip to sidebar Skip to footer

How To Float Divs Left With Shorter Divs One Below Anoter

I have a list of dynamically generated divs that represent panels for selecting various options. There are two types of divs, regular ones and short ones. The height of the regular

Solution 1:

As far as I can see, this is not possible purely with CSS: If you provide the small boxes with clear: left, they will appear below all others. If you don't, they will appear next to each other.

The simplest workaround I can think of is to manually group two small boxes into a separate div. Here's a working example:

<html>
<head>
    <style type="text/css">
        div.large, div.small { width: 40px; margin: 5px; }
        div.large { height: 95px; background-color: blue; }
        div.small { height: 45px; background-color: red; }
        div.large, div.smallblock { float: left; }
    </style>
</head>
<body>
    <div class="large">1</div>
    <div class="large">2</div>
    <div class="smallblock">
        <div class="small">3</div>
        <div class="small">4</div>
    </div>
    <div class="smallblock">
        <div class="small">5</div>
        <div class="small">6</div>
    </div>
    <div class="large">7</div>
</body>
</html>

Solution 2:

There is no generic pure CSS solution.

See a previous answer of mine for a comparison of the candidate techniques:

Unless you can use server-side code to manually calculate pixels and use position: relative / position: absolute; top: ?px; left: ?px, you will have to resort to JavaScript to handle the positioning.

This jQuery plugin is generally a good solution: jQuery Masonry

There's also a raw JavaScript version: Vanilla Masonry

I find myself recommending it somewhat regularly:

https://stackoverflow.com/search?q=user%3A405015+masonry

Some possibly relevant demos:


Post a Comment for "How To Float Divs Left With Shorter Divs One Below Anoter"