tags:

views:

176

answers:

4

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

+3  A: 

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.

John Feminella
or just include the random bits as style="..." in the html. Good idea, thanks john
Victor P
+5  A: 

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.

Shtééf
I'm a little confused by this answer. Isn't this 100% deterministic and not random at all?
John Feminella
Yes, it is. But I was under the impression that part of the question was about how to position the elements in the page.
Shtééf
A: 

As far as your Question goes: No its not possible to do just using HTML and CSS.

Juuccy
A: 

I can't be done with just HTML and CSS, your options are:

  • create a style sheet each time with a server side language like PHP and serve the content precalculated to the browser
  • use a basic fixed style sheet and modify the DOM via Javascript

as for the non overlap part, you have to do a bit of math/geometry: generate coordinates for vertexes making sure they don't fall in a previously created box (boring but quite easy) and use position: absolute to place them.

kemp