Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I float elements with different size in a tile

The question is simple. I have a bunch of elements that are going to make a tile. However, some of them have a longer height; let's say twice as much as the other ones. I want all of them to match in a tile just by pure CSS styling.

Here is what I have:

enter image description here

And this is what I want:

enter image description here

Here is my code:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div {
    box-shadow: 0 0 1px black inset;
    width: 100px;
    display: inline-block;
}
#d1,
#d2,
#d4,
#d5,
#d6,
#d8,
#d9{
    height: 100px;
    background-color: yellow;
}
#d7,
#d3{
    height: 200px;
    background-color: red;
}
</style>
</head>
<body>
<div id="d1">1</div><div id="d2">2</div><div id="d3">3</div><div id="d4">4</div><div id="d5">5</div><div id="d6">6</div><div id="d7">7</div><div id="d8">8</div><div id="d9">9</div>
</body>
</html>

And you can try it live on JSBin: http://jsbin.com/usovek/1/edit

Notes:

  • The content is dynamic
  • The number of boxes can vary
  • Any box can be longer. And possibly wider.
  • The width or height of boxes are always a number of units. The unit in this example is 50 and some boxes are 50, some others are 100px high. But It would be perfect if the problem is solved for any number of units (1,2,3... which are 50px, 100px, 150px,...)
like image 443
AlexStack Avatar asked Mar 10 '13 07:03

AlexStack


1 Answers

If your content is static, you can use position absolute blocks inside a relatively positioned container, but if the content is dynamic than you cannot do this with CSS(Only), what you need to use is

jQuery Masonry

Or the best you can do is this

CSS

#d7,
#d3{
    height: 200px;
    background-color: red;
    float: left;
}

3rd Possibility: Wrap the boxes insde containers and float the accordingly

Demo (Only Possible When Things Are Static) :)

like image 55
Mr. Alien Avatar answered Nov 16 '22 16:11

Mr. Alien