开发者

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

i 开发者_StackOverflowwant 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


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜