Can I scatter divs around a page randomly using only HTML and CSS?

css, dom, html

Solution

If the size is fixed, perfectly centering a div is not hard. The trick is to apply negative margins:

#centered {
  width: 400px; height: 200px;
  position: absolute; top: 50%; left: 50%;
  margin-left: -200px; margin-top: -100px;
}

Now, to position other divs relative to this centered div, you use `position: relative`.

Example HTML snippit:

<div id="centered">
  <div id="other"></div>
</div>

And in addition to the above, the following CSS:

#other {
  width: 200px; height: 100px;
  position: relative; top: -150px; left: 180px;
}

Add a border or background color to get a better look at the example:

div {
  border: 1px solid black;
}

If this is not a static page, and you want to randomize on every page load, you could either use Javascript or some server side scripting to create and style divs dynamically.

Problem

i want to have a box in the centre of a page and several boxes scattered around, with different sizes, random positions, and no overlap. I think this is not possible to do with just html and css, and javascript/html DOM is needed. Have you seen examples of this? Do you have any tip or piece of code that can be helpful? Dont mind if it doesnt solve the whole problem, a solution for one of the sub-problems (eg no overlap) will be useful too! Thanks alt text http://img99.imageshack.us/img99/3563/scattered.jpg

Original source