简体   繁体   中英

How to create randomly laid out grid with divs of random sizes

I'm trying to create a site layout similar to this -

http://www.mondieu.nu/mishmash/fashion/

How can I get the divs in the "grid" to be of different sizes and to appear in a layout similar to that? So far I have this bit of jQuery:

$('.post-image img').each(function(){ $(this).css('width', (50+(Math.random()*700))) })

Any help will be appreciated.

There is a little bit of built in order to the site you reference. The first two images look more fixed, both aligned to the top and taking up about half the page (centered). After that it looks like the images are in divs which are floated left and maybe have a random margin to offset them from where they should be. The images within the div then have a random width as you have attempted above.

So if I were you I would start with placing some images (say 10) in a container div and floating them left. I would then play around with adding random offsets to them (random margins or random top/bottom in px's (with position relative or absolute)). You can then try randomly changing the image size.

Finally, once you've got this working you can look at something more ordered at the top to make it look like it's shifting from ordered to random as you scroll down, rather than just starting off random.

One other thing to keep in mind is how this scales on smaller vs larger devices. Float left will just wrap images under each other as you scale down which is cool, if your images can be a % of the page width you could also scale those down to work on smaller pages.

Try this:
$('.post-image img').each(function(){ $(this).css('width', (50+(Math.random()*700)) + 'px'); });

Within .each()

the keyword this refers to the element

you could use this.width = 50 + (Math.random() * 700) to set <img> element width attribute

 $(function() { $(".post-image img").each(function() { this.width = 50 + (Math.random() * 700) }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="post-image"> <img src="http://lorempixel.com/100/100?=1" /> <img src="http://lorempixel.com/100/100?=2" /> <img src="http://lorempixel.com/100/100?=3" /> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM