Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

dom

css

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

like image 530
Victor Avatar asked Jan 30 '10 14:01

Victor


2 Answers

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.

like image 68
Stéphan Kochen Avatar answered Nov 15 '22 08:11

Stéphan Kochen


I assume you want to randomize on every page load, so that different users see different things. If so, this isn't possible with only HTML and CSS. CSS is designed to be deterministic and reproducible in a consistent way, which is the opposite of what you're going for here.

However, a clever way around this would be to link in a stylesheet from a dynamic page which itself serves random CSS. For example, have something like the following:

<link rel="stylesheet" type="text/css" href="styles.php"/>

where styles.php is a PHP page that generates the random CSS.

like image 32
John Feminella Avatar answered Nov 15 '22 06:11

John Feminella